Emil Østervig Emil Østervig - 3 months ago 14
jQuery Question

Javascript each loop through sliders settings

I'm trying to do an each loop for the settings of my slick sliders.

The content in settings is as following:

$('.slider1').slick({
dots: false,
infinite: true,
swipe: false,
speed: 300,
slidesToShow: 4,
slidesToScroll: 1,
prevArrow: ".pp1",
nextArrow: ".nn1",
});

$('.slider2').slick({
dots: false,
infinite: true,
swipe: false,
speed: 300,
slidesToShow: 4,
slidesToScroll: 1,
prevArrow: ".pp2",
nextArrow: ".nn2",
});


So each slider needs basically the same settings, But with the selector and the class in
prevArrow
and
nextArrow
upping one for each. They all have a common parent wrapper called
.slider-wrapper
.

I guess I have to do a each loop of the parent, get child element.

slider
+=1
and use
+=1
at the
prev/next
settings as well.

var prev = '.pp';
var next = '.nn';
var sliders = '.slider';
function prevAdd() {
return prev += 1;
};

function nextAdd() {
return next += 1;
};

function slidersAdd() {
return sliders += 1;
};

$.each('.slider-wrapper').child(slidersAdd()).slick({
prevArrow: prevAdd(),
// various settings
});


This is probably full of errors, But it's pretty much the best I could work out on my own.

EDIT: Html markup

<div class="slider-wrapper">
<div class="slider-nav>
<button class="pp1">prev</button>
<button class="nn1">next</button>
</div>
<div class="slider1">
<!-- list of divs for slider elements. Irrelevant for problem -->
</div>
</div>

<div class="slider-wrapper">
<div class="slider-nav>
<button class="pp2">prev</button>
<button class="nn2">next</button>
</div>
<div class="slider2">
<!-- list of divs for slider elements. Irrelevant for problem -->
</div>
</div>


and so on with multiple sliders.

Answer

If your sliders all have the class slider, then you could do this, applying the each method on the selected element collection:

$('.slider-wrapper .slider').each(function (index, slider) {
    var id = index + 1; 
    $(slider).slick({
        prevArrow: ".pp" + id,
        nextArrow: ".nn" + id,
        // various settings
    });
});

If you don't have the slider class on every slider element, but a class with a unique number suffixed to it, then use this selector:

$('.slider-wrapper [class^=slider]').each( // ...etc

But really, you should not assign different classes to each slider. A class name is not a unique identifier. You can reuse it for similar elements.