How to use SyntaxHighlighter on a sharepoint 2013 blog (Office365)? - javascript

I'm trying to allow code highlighting using SyntaxHighlighter on a sharepoint 2013 blog site (office365 portal).
Here is the code I have put in the head of the masterpage (js and css ressources are loaded before) :
<script type="text/javascript">
function sh(){
SyntaxHighlighter.highlight();
};
// executed when SP load completes
_spBodyOnLoadFunctionNames.push("sh");
</script>
The _spBodyOnLoadFunctionNames should provide a mechanism to run functions after the load page event, but it seems it's never executed.
Running my sh function from the developper tool (console) is working as expected.
Does anybody have a clue, am I using the right event ?

_spBodyOnLoadFunctionNames array declared in init.js (it is a part of SharePoint JavaScript Library)
According to init.js:
AttachEvent("DOMContentLoaded", _spBodyOnLoadWrapper, document);
window.onload = _spBodyOnLoadWrapper;
where
function _spBodyOnLoadWrapper() {
ExecuteOrDelayUntilScriptLoaded(ProcessDefaultOnLoad, "core.js");
//the remaining code is omitted for clarity..
}
function ProcessDefaultOnLoad() {
ProcessOnLoadFunctionNames(_spBodyOnLoadFunctionNames);
//the remaining code is omitted for clarity..
}
function ProcessOnLoadFunctionNames(onLoadFunctionNames) {
if (onLoadFunctionNames != null) {
for (var i = 0; i < onLoadFunctionNames.length; i++) {
var expr = "if(typeof(" + onLoadFunctionNames[i] + ")=='function'){" + onLoadFunctionNames[i] + "();}";
eval(expr);
}
onLoadFunctionNames = [];
}
}
To summarize, the specified approach is a proper mechanism to run functions after the load page event.
In fact it works for me just fine (see the picture below)
Make sure init.js library is loaded before _spBodyOnLoadFunctionNames is initialized.
Alternatively you could try the following approach:
<script type="text/javascript">
function sh(){
SyntaxHighlighter.highlight();
};
ExecuteOrDelayUntilScriptLoaded(sh, "core.js");
</script>
Results

+Vadim Gremyachev's answer is valid with IE, but doesnt work with chrome, here is the workaround I've used (inspirated from https://stackoverflow.com/a/2956980/381149 ):
function sh(){
SyntaxHighlighter.highlight();
};
function setIntervalX(callback, delay, repetitions) {
var x = 0;
var intervalID = window.setInterval(function () {
callback();
if (++x === repetitions) {
window.clearInterval(intervalID);
}
}, delay);
}
$(document).ready(function () {
if( $('.syntaxhighlighter').length == 0 ){
setIntervalX(function() { sh() }, 1000,5);
}
$("a").on("click",function () {
if( $('.syntaxhighlighter').length == 0 ){
setIntervalX(function() {
sh()
}, 1000,5);
}
return true;
});
});

Related

How to pass variable asyncronously through different scripts

I can't figure out how to do it.
I have two separate scripts. The first one generates an interval (or a timeout) to run a specified function every x seconds, i.e. reload the page.
The other script contains actions for a button to control (pause/play) this interval.
The pitfall here is that both sides must be asyncronous (both run when the document is loaded).
How could I properly use the interval within the second script?
Here's the jsFiddle: http://jsfiddle.net/hm2d6d6L/4/
And here's the code for a quick view:
var interval;
// main script
(function($){
$(function(){
var reload = function() {
console.log('reloading...');
};
// Create interval here to run reload() every time
});
})(jQuery);
// Another script, available for specific users
(function($){
$(function(){
var $playerButton = $('body').find('button.player'),
$icon = $playerButton.children('i');
buttonAction = function(e){
e.preventDefault();
if ($(this).hasClass('playing')) {
// Pause/clear interval here
$(this).removeClass('playing').addClass('paused');
$icon.removeClass('glyphicon-pause').addClass('glyphicon-play');
}
else {
// Play/recreate interval here
$(this).removeClass('paused').addClass('playing');
$icon.removeClass('glyphicon-play').addClass('glyphicon-pause');
}
},
buttonInit = function() {
$playerButton.on('click', buttonAction);
};
buttonInit();
});
})(jQuery);
You could just create a simple event bus. This is pretty easy to create with jQuery, since you already have it in there:
// somewhere globally accessible (script 1 works fine)
var bus = $({});
// script 1
setInterval(function() {
reload();
bus.trigger('reload');
}, 1000);
// script 2
bus.on('reload', function() {
// there was a reload in script 1, yay!
});
I've found a solution. I'm sure it's not the best one, but it works.
As you pointed out, I eventually needed at least one global variable to act as a join between both scripts, and the use of a closure to overcome asyncronous issues. Note that I manipulate the button within reload, just to remark that sometimes it's not as easy as moving code outside in the global namespace:
Check it out here in jsFiddle: yay! this works!
And here's the code:
var intervalControl;
// main script
(function($){
$(function(){
var $playerButton = $('body').find('button.player'),
reload = function() {
console.log('reloading...');
$playerButton.css('top', parseInt($playerButton.css('top')) + 1);
};
var interval = function(callback) {
var timer,
playing = false;
this.play = function() {
if (! playing) {
timer = setInterval(callback, 2000);
playing = true;
}
};
this.pause = function() {
if (playing) {
clearInterval(timer);
playing = false;
}
};
this.play();
return this;
};
intervalControl = function() {
var timer = interval(reload);
return {
play: function() {
timer.play();
},
pause: function(){
timer.pause();
}
}
}
});
})(jQuery);
// Another script, available for specific users
(function($){
$(function(){
var $playerButton = $('body').find('button.player'),
$icon = $playerButton.children('i'),
interval;
buttonAction = function(e){
e.preventDefault();
if ($(this).hasClass('playing')) {
interval.pause();
$(this).removeClass('playing').addClass('paused');
$icon.removeClass('glyphicon-pause').addClass('glyphicon-play');
}
else {
interval.play();
$(this).removeClass('paused').addClass('playing');
$icon.removeClass('glyphicon-play').addClass('glyphicon-pause');
}
},
buttonInit = function() {
$playerButton.on('click', buttonAction);
interval = intervalControl();
};
buttonInit();
});
})(jQuery);
Any better suggestion is most welcome.

HTML5 Ajaxify - clashes with other simple jquery scripts

So I'm trying to implement this on my website – https://github.com/browserstate/ajaxify
Works fine on most pages, but there are two pages that rely on two simple scripts. The first one is
jQuery(function() {
var adjustArticleHeights = (function () {
var leftColumnHeight = 0,
rightColumnHeight = 0,
$articles = jQuery('.shop-item');
for (var i = 0; i < $articles.length; i++) {
if (leftColumnHeight > rightColumnHeight) {
rightColumnHeight += $articles.eq(i).addClass('right').outerHeight(true);
} else {
leftColumnHeight += $articles.eq(i).outerHeight(true);
}
}
return $articles;
})();
});
But the weird thing is, if I'm on another page. Then go to this page, the script doesn't work. Then if I refresh the page, the script does work.
The second script below, it doesn't fire at all. No matter how many times I refresh
function() {
jQuery('.image-caption').hide();
jQuery('.image-hover ').hover( function() {
jQuery(this).find('.image-caption').fadeIn(300);
}, function() {
jQuery(this).find('.image-caption').fadeOut(300);
});
};
I also now get an error "Uncaught SyntaxError: Unexpected token {" on line 1.
Just call it.
try
function() {
jQuery('.image-caption').hide();
jQuery('.image-hover ').hover( function() {
jQuery(this).find('.image-caption').fadeIn(300);
}, function() {
jQuery(this).find('.image-caption').fadeOut(300);
});
}();
note "()"

Passing functions between RequireJS files

I've got a file which needs to run on page load (randomise_colors.js), but also needs to be called by another file as part of a callback function (in infinite_scroll.js). The randomise_colors script just loops through a list of posts on the page and assigns each one a color from an array which is used on the front-end.
Infinite Scroll loads new posts in to the DOM on a button click, but because the randomise_colors.js file has already ran on page load, new content loaded is not affected by this so I need it to run again. I'm open to other suggestions if it sounds like I could be tackling the problem in a different way, I'm no JS expert.
Currently I'm getting Uncaught ReferenceError: randomise_colours is not defined referring this line of infinite_scroll.js:
randomise_colours.init();
I'm calling all files that need be loaded on document.ready in app.js
require(['base/randomise-colours', 'base/infinite-scroll'],
function(randomise_colours, infinite_scroll) {
var $ = jQuery;
$(document).ready(function() {
infinite_scroll.init();
randomise_colours.init();
});
}
);
This is infinite_scroll.js which initialises Infinite Scroll and features the callback. The callback function runs whenever new items are loaded in via AJAX using the Infinite Scroll jQuery plugin. I've put asterix around the area where I need to run the randomise_colors.init() function from randomise_colors.js.
define(['infinitescroll'], function() {
var $ = jQuery,
$loadMore = $('.load-more-posts a');
function addClasses() {
**randomise_colours.init();**
};
return {
init: function() {
if($loadMore.length >= 1) {
this.setUp();
} else {
return false;
}
},
setUp: function() {
this.initInfiniteScroll();
},
initInfiniteScroll: function() {
$('.article-listing').infinitescroll({
navSelector : '.load-more-posts',
nextSelector : '.load-more-posts a',
itemSelector : '.standard-post'
}, function(newItems) {
addClasses();
});
//Unbind the standard scroll-load function
$(window).unbind('.infscr');
//Click handler to retrieve new posts
$loadMore.on('click', function() {
$('.article-listing').infinitescroll('retrieve');
return false;
});
}
};
});
And this is my randomise_colors.js file which runs fine on load, but needs to be re-called again after new content has loaded in.
define([], function() {
var $ = jQuery,
$colouredSlide = $('.image-overlay'),
colours = ['#e4cba3', '#867d75', '#e1ecb9', '#f5f08a'],
used = [];
function pickRandomColour() {
if(colours.length == 0) {
colours.push.apply(colours, used);
used = [];
}
var selected = colours[Math.floor(Math.random() * colours.length)];
var getSelectedIndex = colours.indexOf(selected);
colours.splice(getSelectedIndex, 1);
used.push(selected);
return selected;
};
return {
init: function() {
if($colouredSlide.length >= 1) {
this.setUp();
} else {
return false;
}
},
setUp: function() {
this.randomiseColours();
},
randomiseColours: function() {
console.log('randomise');
$colouredSlide.each(function() {
var newColour = pickRandomColour();
$(this).css('background', newColour);
});
}
};
});
You would have to reference randomiseColours inside the infiniteScroll file. So you need to change your define function to the following:
define(['infinitescroll', 'randomise-colours'], function(infiniteScroll, randomise_colours)
Remember that when using require you need to reference all variables through the define function, otherwise they will not be recognised.

How to for loop in casperjs

I am trying to click a 'next' button N number of times and grab the page source each time. I understand that I can run an arbitrary function on the remote website, so instead of click() I just use the remote function nextPage() How do I run the following, an arbitrary number of times:
var casper = require('casper').create();
casper.start('http://www.example.com', function() {
this.echo(this.getHTML());
this.echo('-------------------------');
var numTimes = 4, count = 2;
casper.repeat(numTimes, function() {
this.thenEvaluate(function() {
nextPage(++count);
});
this.then(function() {
this.echo(this.getHTML());
this.echo('-------------------------');
});
});
});
'i' here is an index I tried to use in a javascript for loop.
So tl;dr: I want lick 'next', print pages source, click 'next', print page source, click 'next'... continue that N number of times.
First, you can pass a value to the remote page context (i.e. to thenEvaluate function like this:
this.thenEvaluate(function(remoteCount) {
nextPage(remoteCount);
}, ++count);
However, Casper#repeat might not be a good function to use here as the loop would NOT wait for each page load and then capture the content.
You may rather devise a event based chaining.
The work-flow of the code would be:
Have a global variable (or at-least a variable accessible to the functions mentioned below) to store the count and the limit.
listen to the load.finished event and grab the HTML here and then call the next page.
A simplified code can be:
var casper = require('casper').create();
var limit = 5, count = 1;
casper.on('load.finished', function (status) {
if (status !== 'success') {
this.echo ("Failed to load page.");
}
else {
this.echo(this.getHTML());
this.echo('-------------------------');
}
if(++count > limit) {
this.echo ("Finished!");
}
else {
this.evaluate(function(remoteCount) {
nextPage(remoteCount);
// [Edit the line below was added later]
console.log(remoteCount);
return remoteCount;
}, count);
}
});
casper.start('http://www.example.com').run();
NOTE: If you pages with high load of JS processes etc. you may also want to add a wait before calling the nextPage :
this.wait(
1000, // in ms
function () {
this.evaluate(function(remoteCount) {
nextPage(remoteCount);
}, count);
}
);
[EDIT ADDED] The following event listeners will help you debug.
// help is tracing page's console.log
casper.on('remote.message', function(msg) {
console.log('[Remote Page] ' + msg);
});
// Print out all the error messages from the web page
casper.on("page.error", function(msg, trace) {
casper.echo("[Remote Page Error] " + msg, "ERROR");
casper.echo("[Remote Error trace] " + JSON.stringify(trace, undefined, 4));
});
You could try using Casper#repeat
This should do, for the most part, what you want:
var numTimes = 10, count = 1;
casper.repeat(numTimes, function() {
this.thenEvaluate(function(count) {
nextPage(count);
}, ++count);
this.then(function() {
this.echo(this.getHTML());
this.echo('-------------------------');
});
});
var global_page_links = [];
casper.then(function(){
for(var i=1; i<=5; i++){
// you just add all your links to array, and use it in casper.each()
global_page_links.push(YOUR_LINK);
}
this.each(global_page_links, function(self, link) {
if (link){
self.thenOpen(link, function() {
console.log("OPENED: "+this.getCurrentUrl());
// do here what you need, evaluate() etc.
});
}
});
});
This is answer to question, how to use for() in casperjs to launch several links

jQuery function attr() doesn't always update img src attribute

Context: On my product website I have a link for a Java webstart application (in several locations).
My goal: prevent users from double-clicking, i. e. only "fire" on first click, wait 3 secs before enabling the link again. On clicking, change the link image to something that signifies that the application is launching.
My solution works, except the image doesn't update reliably after clicking. The commented out debug output gives me the right content and the mouseover callbacks work correctly, too.
See it running here: http://www.auctober.de/beta/ (click the Button "jetzt starten").
BTW: if anybody has a better way of calling a function with a delay than that dummy-animate, let me know.
JavaScript:
<script type="text/javascript">
<!--
allowClick = true;
linkElements = "a[href='http://www.auctober.de/beta/?startjnlp=true&rand=1249026819']";
$(document).ready(function() {
$('#jnlpLink').mouseover(function() {
if ( allowClick ) {
setImage('images/jetzt_starten2.gif');
}
});
$('#jnlpLink').mouseout(function() {
if ( allowClick ) {
setImage('images/jetzt_starten.gif');
}
});
$(linkElements).click(function(evt) {
if ( ! allowClick ) {
evt.preventDefault();
}
else {
setAllowClick(false);
var altContent = $('#jnlpLink').attr('altContent');
var oldContent = $('#launchImg').attr('src');
setImage(altContent);
$(this).animate({opacity: 1.0}, 3000, "", function() {
setAllowClick(true);
setImage(oldContent);
});
}
});
});
function setAllowClick(flag) {
allowClick = flag;
}
function setImage(imgSrc) {
//$('#debug').html("img:"+imgSrc);
$('#launchImg').attr('src', imgSrc);
}
//-->
</script>
A delay can be achieved with the setTimeout function
setTimeout(function() { alert('something')}, 3000);//3 secs
And for your src problem, try:
$('#launchImg')[0].src = imgSrc;
Check out the BlockUI plug-in. Sounds like it could be what you're looking for.
You'll find a nice demo here.
...or just use:
$(this).animate({opacity: '1'}, 1000);
wherever you want in your code, where $(this) is something that is already at opacity=1...which means everything seemingly pauses for one second. I use this all the time.
Add this variable at the top of your script:
var timer;
Implement this function:
function setFlagAndImage(flag) {
setAllowClick(flag);
setImage();
}
And then replace the dummy animation with:
timer = window.setTimeout(function() { setFlagAndImage(true); }, 3000);
If something else then happens and you want to stop the timer, you can just call:
window.clearTimeout(timer);

Categories