Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Onclick function toggleClass() issue with two div at a time

I using same onclick function on two span, When clicking on text 1 span it is adding active class and when clicking again removing the class. It is working fine on both span’s.
I just want if when clicked text 1 span so the active class is added to text 1 span and when i click on text 2 span add active class to this span but remove it from text 1 span.
Available on codepen https://codepen.io/hnpiocyj-the-encoder/pen/VwRZBrW

<span class="selected" onclick="select(this);">text 1</span>
<span class="selected" onclick="select(this);">text 2</span>
function select(i){
    e = window.event
    $(i).toggleClass("active");
    e.stopPropagation();
}

I want if text 1 span has active class and when i click on text 2 span add active class but also i want to remove the active class from text 1 span.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You just need to get all the active spans in your function and remove the active class from them. After removing, you can make use of your this object, passed in the function argument, to add a new active class.

See the demo below:

function select(currObj) {
  const allActiveSpans = document.querySelectorAll('span.active');
  allActiveSpans.forEach(span => {
    if(span !== currObj){
      span.classList.remove('active');
    }
  });
  currObj.classList.toggle('active');
}
.active {
  border: 1px solid;
}
<span onclick="select(this);">text 1</span>
<span onclick="select(this);">text 2</span>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading