Home > Software design >  How to make the event listener only add CSS element on one item at a time (vanilla JavaScript)
How to make the event listener only add CSS element on one item at a time (vanilla JavaScript)

Time:02-22

1

^I would like to be able for the style to be enabled for only one at a time.

2

^I'm able to do this, which I don't want the user to be able to do.

So it's weirdly hard framing a question for what is possibly an easy solution. I basically have a list of build versions where I want the user to select one. When one of the versions are selected, it adds a border to the item to display that its clicked. However, with my code right now the user is able to select all 3 items and enable their CSS elements. I would like for the user to be able to only "activate" one item from the list.

HTML and CSS:

<ul >
      
         <li><p><a href="#" >Stable</a></p></li>
        <li><p><a href="#" >Preview</a></p></li>
        <li><p><a href="#" >LTS</a></p></li>
</ul>

<style>
.colorText {
        background-color: #58a7ed;
        color: white;
}
</style>

and the JS stuff:

const btn = document.querySelectorAll('.links');

for (let i = 0; i < btn.length; i   ) {
    btn[i].addEventListener("click", function() {
        btn[i].classList.add('colorText')
    })
}

I really hope I made myself clear, I feel like I'm failing my English trying to word this right lol.

CodePudding user response:

You can also use a forEach loop, accessing the clicked link using event.target

const btns = document.querySelectorAll('.links');

btns.forEach(btn => {
  btn.addEventListener('click', e => {
    // remove any existing active links
    btns.forEach(b => b.classList.remove('colorText'));
    // activate the clicked link
    e.target.classList.add('colorText');
  })
});
.colorText {
  background-color: #58a7ed;
  color: white;
}
<ul >
  <li>
    <p><a href="#" >Stable</a></p>
  </li>
  <li>
    <p><a href="#" >Preview</a></p>
  </li>
  <li>
    <p><a href="#" >LTS</a></p>
  </li>
</ul>

CodePudding user response:

Just before you add the colorText class to the desired item, we can remove colorText from ALL of them, ensuring that only 1 at a time gets the class.

// the rest is the same...
btn[i].addEventListener("click", function() {
  // remove it from all:
  btn.forEach(function(item) {
    item.classList.remove('colorText');
  });
  // add it back to the desired one
  btn[i].classList.add('colorText')
})

CodePudding user response:

you can also use simple for of

const btn = document.querySelectorAll(".links");

for (let bt of btn) {
  bt.addEventListener("click", (e) => {
    btn.forEach((b) => b.classList.remove("colorText"));
    e.target.classList.add("colorText");
  });
}

  • Related