I have two sliders.
The sliders are operated by arrows.
The sliders and arrows have the same class.
At the moment when one of the arrows on Slider A is pressed, BOTH slider A and slider B move.
Is it possible to click the arrow on slider A and only have slider A move WITHOUT changes classes or using ids.
Here is code for the sliders:
HTML:
<div class="slider">
<div class="arrow-left"></div>
<div class="slide"></div>
<div class="slide on"></div>
<div class="slide"></div>
<div class="arrow-right"></div>
</div>
<div class="slider">
<div class="arrow-left"></div>
<div class="slide"></div>
<div class="slide on"></div>
<div class="slide"></div>
<div class="arrow-right"></div>
</div>
CSS:
.slider {
display: flex;
justify-content: space-between;
margin-top: 100px;
padding-right: 10px;
padding-left: 10px;
width: 90%;
margin-left: auto;
margin-right: auto;
align-items: center;
}
.slide {
background-color: red;
width: 150px;
height: 50px;
margin-left: 50px;
margin-right: 50px;
position: relative;
opacity: 0.5;
}
.arrow-left {
background: url('../images/arrowleft.svg');
width: 50px;
cursor: pointer;
height: 50px;
background-repeat: no-repeat;
z-index: 5;
}
.arrow-right {
background: url('../images/arrowright.svg');
width: 50px;
height: 50px;
cursor: pointer;
background-repeat: no-repeat;
z-index: 5;
}
.on {
height: 500px;
min-width: 300px;
opacity: 1;
}
Javascript
$('.slider').each(function() {
$(this).find('.arrow-left').on("click", function() {
$('.slide').animate({
left: "-=33%"
})
$('.on').next().addClass('on')
$('.on').prev().removeClass('on')
})
$(this).find('.arrow-right').on("click", function() {
$('.slide').animate({
left: "+=33%"
})
$('.on').prev().addClass('on')
$('.on').next().removeClass('on')
})
})
>Solution :
You can do like this, saving the jQuery element of the slider you are working on as a function local variable to restrict the class selections with find
$('.slider').each(function() {
var _slider = $(this);
_slider.find('.arrow-left').on("click", function() {
_slider.find('.slide').animate({
left: "-=33%"
})
_slider.find('.on').next().addClass('on')
_slider.find('.on').prev().removeClass('on')
})
_slider.find('.arrow-right').on("click", function() {
_slider.find('.slide').animate({
left: "+=33%"
})
_slider.find('.on').prev().addClass('on')
_slider.find('.on').next().removeClass('on')
})
})
Not tested but it should work
NOTE: you should also be able to chain the addClass
and removeClass
too. Because once you added the class, the second line now selects 2 elements (with the one you just added the class on) and can lead to unexpected things. Chaining the calls should solve this (you need an extra prev
or next
here)
_slider.find('.on').next().addClass('on').prev().prev().removeClass('on')
or with a variable similar to slider
var _on = _slider.find('.on');
_on.next().addClass('on');
_on.prev().removeClass('on');