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() {
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 ) {
Now we can keep all our code in one window.load function but only reference the nivoSlider() if we have slides to nivo.

  1. Oct 12, 2012 8:07 pm

    Can you show me an example of the Nivo slider and do you think that it would be hard to incorporate into this site?

Write Comment...