views:

43

answers:

6

So I have this nice slider script that I want to use on this page: http://tuscaroratackle.com/rods for several instances on the page. (In other words each rod posting will have it's own slider, a total of about 11 sliders on the page)

In order to run the script I have to include this function declaration:

$(document).ready(function(){   
    $("#rod-slider1").easySlider();
     $("#rod-slider2").easySlider();
     $("#rod-slider3").easySlider();
     $("#rod-slider4").easySlider();
     $("#rod-slider5").easySlider();
     $("#rod-slider6").easySlider();
     $("#rod-slider7").easySlider();
     $("#rod-slider8").easySlider();
     ...etc...
  });

So the question here (is a jQ noob question I know) is can I combine those lines into one by adding all the ID selectors into the first function? And if so, what would be the proper format for writing it that way?

+6  A: 

You can also use a class:

$(document).ready(function(){   
    $(".rod-slider").easySlider();
});

The slider will now be applied to all/any elements having the class rod-slider.

If you want/need to use ids, you can do so by separating them with a comma:

$(document).ready(function(){   
    $("#rod-slider1, #rod-slider2, #rod-slider3, #etc").easySlider();
});

Or you can use the add method.

If you don't want to modify you current html, you can use the starts with selector:

$(document).ready(function(){   
    $("[id^='rod-slider']").easySlider();
});
Sarfraz
Unfortunately it turns out that the script does not allow me to use a class, as it is producing control buttons with ID's, so I have to label each slider with an individual ID.
JAG2007
+1  A: 
$(".rodslider").easySlider(); 

Where "rodslider" is a class and not an id selector. 
brumScouse
+1  A: 

Give them all a common class, then use a .class selector, like this:

$(function(){   
  $(".rod-slider").easySlider();
});
Nick Craver
+1  A: 

You can add a class and select them all together. For example if they are DIVs you can just do this way

<div class="rodslider"></div>

and

$(document).ready(function(){   
    $("div.rodslider").easySlider();
});
Lorenzo
+2  A: 

You can use the starts-with selector

$(document).ready(function(){   
     $("[id^='rod-slider']").easySlider();
  });

This translates to select all elements that have an id attribute that starts with rod-slider

You can improve the performance of this if you know the tag name is the same for all elements. For example if they are all divs you could write it as

$("div[id^='rod-slider']").easySlider();

for better performance..

Gaby
+1  A: 

You could do:

$(document).ready(function(){
    for (var i = 1; i <= 8; i++) {
        $("#rod-slider" + i).easySlider();
    }
});

or just use the class selector...

$(document).ready(function(){
    $(".rod-slider").easySlider();
});
David