Home > Software design >  Javascript class add/remove only working once
Javascript class add/remove only working once

Time:11-23

I'm trying to write some js that adds an extra class of .active to an already existing class called .option on click. As well as removing said .active class from anoy div with both classes .option.active.

This is what I have so far

console.log(`It Works!`);

const option = document.querySelector(`.option:not(.active)`);
const activeOption = document.querySelector(`.option.active`);


function handleClickAdd() {
        console.log(`IT GOT ADDED`);
        option.classList.add('active');
        
}
function handleClickRemove() {
  console.log(`IT GOT REMOVED`);
  activeOption.classList.remove(`active`);
  
}


option.addEventListener(`click`, handleClickAdd);
activeOption.addEventListener(`click`, handleClickRemove);

the console is returning the logs, but both the add and remove functions are only seeming to work once. Is there a way i can make it continue so that you can toggle about the options?

Please bear in mind I am very new to Javascript and only halfway through a beginners course!

many thanks in advance

Ive added console logs to the functions to see that they are definietly running

CodePudding user response:

activeOption.classList.toggle("active");

this is one function that does both ways. In case there is already this class, it'll remove it. if not - it'll add that

CodePudding user response:

Using toggle as suggested by @Yosi, a working example below.

ul element is attached click event.

Based on the list item which is clicked, class is added or removed on the specific list item.

console.log(`It Works!`);

const option = document.getElementsByTagName(`ul`)[0];

function handleClickAddRemove(e) {
  console.log(`IT GOT ADDED OR REMOVED`, e.target.classList.value);
  e.target.classList.toggle('active');
}

option.addEventListener(`click`, handleClickAddRemove);
<ul>
  <li >1</li>
  <li >2</li>
  <li >3</li>
  <li >4</li>
  <li >5</li>
</ul>

  • Related