Home > Net >  changing the class when the button is clicked
changing the class when the button is clicked

Time:11-05

it is necessary that when you click on the button, the 'active' class is removed from the first div, and added to the second. When pressed again, the active class was removed from the active block and added to the next one, and so on until the end

<div >
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
</div>
<button >Next</button>
.main {
  display: flex;
}

.block {
  width: 8px;
  height: 16px;
  background: #767676;
  margin: 5px;
}

.active {
  height: 26px;
}

.next {
  padding: 5px;
}
const btn = document.querySelector('.next');
btn.addEventListener(`click`, e => {
 document.querySelectorAll(`.main > .block:not(.active)`)[0].classList  = ` active`;
});

CodePudding user response:

Here is my solution. Please use the following javascript code:

    const btn = document.querySelector('.next');
    btn.addEventListener(`click`, e => {
        const currentActive = document.querySelector('.main > .block.active');
        let nextActive;
        if (currentActive === document.querySelector('.main').lastElementChild) {
            nextActive = document.querySelector('.main > .block:first-child');
        } else {
            nextActive = currentActive.nextElementSibling;
        }
        currentActive.classList.remove('active');
        nextActive.classList.add('active');
    });

CodePudding user response:

This snippet should do the trick.

First, you remove the "active" class from all elements. Then you re-add the "active" class to the element which comes next.

let currentIndex = 0;

const handleNext = () => {
  currentIndex  ;
  const elements = document.getElementsByClassName("block");
  Array.prototype.forEach.call(elements, elem => {
    elem.classList.remove("active")
   });
   
   if (currentIndex >= elements.length) return;
   elements[currentIndex].classList.add("active");
};
.main {
  display: flex;
}

.block {
  width: 8px;
  height: 16px;
  background: #767676;
  margin: 5px;
}

.active {
  height: 26px;
}

.next {
  padding: 5px;
}
<div >
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
</div>
<button  onClick="handleNext()">Next</button>

  • Related