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.
>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>