Call jQuery NivoSlider Function if Slider Exists in WordPress


So here’s an interesting issue. Let’s say you want to have a Nivo Slider on the homepage of your theme. You obviously only want to call that nivoSlider.js if you’re on the homepage. Most of the time you’ll also put your $(window).load function inline with the HTML markup for the slider so you can also wrap it in a is_home conditional. This way your call to the nivoSlider.js and the HTML markup for the slider only show on the homepage.

This isn’t pretty cause we don’t like inline scripts and function calls, right?

So then we can create an external .js file to hold this code
[code lang=”js”]$(window).load(function() {
$(‘#slider’).nivoSlider();
});[/code]
There’s a problem with this. You can end up with multiple $(window).load function’s because you may need another function to do something on every part of the site. For example on window load you may want to remove all hard coded pixel based width and height attributes from images.

Here’s a solution for calling the nivoSlider() function ONLY if the #slider selector exists.
[code lang=”js”]$(window).load(function() {
if( $(‘#slider’).length ) {
$(‘#slider’).nivoSlider();
}
});[/code]
Now we can keep all our code in one window.load function but only reference the nivoSlider() if we have slides to nivo.


One response to “Call jQuery NivoSlider Function if Slider Exists in WordPress”

Leave a Reply

Your email address will not be published. Required fields are marked *