user1686277
user1686277

Reputation: 37

Is there a cleaner way of writing this jQuery?

Could I write this into a loop?

$(document).ready(function(){
    $('#slideItems1').bxSlider();
    $('#slideItems2').bxSlider();
    $('#slideItems3').bxSlider();
    $('#slideItems4').bxSlider();
    $('#slideItems5').bxSlider();
});

I am using bxSlider and for using multiple galleries you need to call the slider and associate it to each item. I have over 200 products sometimes per page.

Upvotes: 2

Views: 148

Answers (5)

Haribol
Haribol

Reputation: 11

I recommend that give the class name for that and access that using class name.

//slideritem is class name which you give to all which has to slider div

$(function()
{

    $('.slideritem').bxSlider();
});

Upvotes: 0

James Allardice
James Allardice

Reputation: 165971

You could use an attribute starts-with selector to select all elements with an ID that starts with "slideItems":

$('[id^="slideItems"]').bxSlider();

This is the case with the majority of jQuery methods (and most plugins will allow it too). The method is applied to every element in the matched set, so there's no need for a loop. You can see how the plugin you're using implements this functionality in its source (notice the call to each, and note that this refers to the jQuery object containing the matched set of elements):

this.each(function(){
    // make sure the element has children
    if($(this).children().length > 0){
        base.initShow();
    }
});

Upvotes: 10

Rune FS
Rune FS

Reputation: 21742

The short but not optimal rewrite would be (if the list of slideitems is fixed)

$(function(){
    $('#slideItems1, #slideItems2, #slideItems3, #slideItems4, #slideItems5').bxSlider();
});

however I would highly recommend simply to give them all a class. Say slideritem and do

$(function(){
    $('.slideritem').bxSlider();
});

Upvotes: 2

gen_Eric
gen_Eric

Reputation: 227240

Give all the elements a class, then select them using that class.

$('.slideItems').bxSlider();

Upvotes: 3

472084
472084

Reputation: 17885

Give all your slide items a class and then just do $('.slideItem').bxSlider();

Upvotes: 6

Related Questions