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

$(window).load(function() {
$('#slider').nivoSlider();
});

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.

$(window).load(function() {
if( $('#slider').length ) {
$('#slider').nivoSlider();
}
});

Now we can keep all our code in one window.load function but only reference the nivoSlider() if we have slides to nivo.

One thought on “Call jQuery NivoSlider Function if Slider Exists in WordPress

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s