I'm struggling with removing 'active' class from a link that is already selected.
Looking at the line 20 in JavaScript. Shouldn't classLink.toggle add / remove "active" on clickedElement? I even tried few approaches like
if (clickedElement.classList.contains('active')) {
clickedElement.classList.remove('active');
} else {
clickedElement.classList.add('active');
}
but none seem to work on this particular class (works fine on any other class i add). What am i missing?
Just to answer the actual question, why toggle
does not untoggle .active
in your fiddle. https://jsfiddle.net/Evenclan/09sn2kd3/15/
What you are doing first, before toggling is:
for (let activeLink of activeLinks) {
activeLink.classList.remove('active');
}
This removes .active
from all link elements. Which means that all those have no class anymore or atleast no class .active
.
In the next line you toggle
the class .active
which was just removed:
clickedElement.classList.toggle('active');
Thus the class gets added back (what is not there gets added, what is there gets removed).
toggle
actually works fine, just your logic does not. To get the desired result you have to exclude the current clicked element from the removing of class.
for (let activeLink of activeLinks) {
if(clickedElement !== activeLink) activeLink.classList.remove('active');
}
clickedElement.classList.toggle('active');