Loek Lemmens Loek Lemmens - 2 months ago 22
Javascript Question

set class active to next slide element

I have a question about Javascript.
You can find my HTML markup below

<div class="slides">
<div class="slide active" id="one"></div>
<div class="slide" id="two"></div>
<div class="slide" id="third"></div>
<div class="slide" id="fourth"></div>
</div>

<button onclick="slide-down()">
Next slide
</button>

<button onclick="slide-up()">
Previous slide
</button>


What can i do if the user click on the button slide-down to remove with pure javascript the class 'active' en set this to the next slide element?

Answer

Something like the below will work. Makes use of many javascript DOM properties and methods. You will need to change the names of your functions slightly as a hyphen is not valid in a name of a function. Ive replaced with underscores.

function slide_down(){
    var elems = document.querySelectorAll(".slide");
    var curr = document.querySelector(".active");
    curr.classList.remove("active");
    if(curr.nextElementSibling)
        curr.nextElementSibling.classList.add("active");
    else
        elems[0].classList.add("active");
}

function slide_up(){
    var elems = document.querySelectorAll(".slide");
    var curr = document.querySelector(".active");
    curr.classList.remove("active");
    if(curr.previousElementSibling)
        curr.previousElementSibling.classList.add("active");
    else
        elems[elems.length-1].classList.add("active");
}
.active{background-color:red}
<div class="slides">
  <div class="slide active" id="one">1</div>
  <div class="slide" id="two">2</div>
  <div class="slide" id="third">3</div>
  <div class="slide" id="fourth">4</div>
</div>

<button onclick="slide_down()">
  Next slide
</button>

<button onclick="slide_up()">
  Previous slide
</button>