Adding a JavaScript class when clicking a link
I have the following links:
<a class="active" href="#section1">Link 1</a>
<a href="#section2">Link 2</a>
When I click on link 2, I would like it to get the active class and remove the class from link 1 itself, so that it really becomes:
<a href="#section1">Link 1</a>
<a class="active" href="#section2">Link 2</a>
This should work both ways. I.e. any click on the link gets the class and removes it from another.
How can this be done using JavaScript / Prototype?
You can write a small helper function using prototype support, which removes the class from all elements activeand adds it to the one you clicked on:
function active(e) {
$$('.active').each(function(i) {
i.removeClassName('active');
});
e.addClassName('active');
};
You can call this function from events onclick:
<a href="#sectiona" onclick="active(this)">a</a>
<a href="#sectionb" onclick="active(this)">b</a>
<a href="#sectionc" onclick="active(this)">c</a>
Try the following:
// initialization
var links = document.links;
for (var i=0; i<links.length; ++i) {
links[i].onclick = function() {
setActive(links, this);
};
}
function setActive(links, activeLink) {
for (var i=0; i<links.length; ++i) {
var currentLink = links[i];
if (currentLink === activeLink) {
currentLink.className += " active";
} else {
currentLink.className = currentLink.className.split(/\s+/).map(function(val) {
return val === "active" ? "" : val;
}).join(" ");
}
}
}