ArtemGoldsmith ArtemGoldsmith - 5 months ago 9
Javascript Question

How to add li class when clicking another div

I have two divs: #slider-next and #slider-prev. Also i have 4 li elements. On each click #slider-next i need to add .active class to each li.
First look:

<ul class="items-list">
<li class="active" id="l1">One</li>
<li id="l2">Two</li>
<li id="l3">Three</li>
<li id="l4">Four</li>
</ul>


After click #slider-next it should looks like:

<ul class="items-list">
<li id="l1">One</li>
<li class="active" id="l2">Two</li>
<li id="l3">Three</li>
<li id="l4">Four</li>
</ul>


It should repeating by clicking like it was at start
Here is my code but it adds class only for a second li:

function arrowNext() {
if( $('#l1, #l2, #l3, #l4').hasClass('active') ) {
$('.items-list li').removeClass('active');
$('li:nth-child(1)').next().addClass('active');
}
}

Answer

I think it's a good way you to follow

$(".next").on("click", function(){
    $(".active").removeClass("active").next("li").addClass("active");
})
$(".prev").on("click", function(){
    $(".active").removeClass("active").prev("li").addClass("active");
})

here's a fiddle: https://jsfiddle.net/v58jzp9L/