I have these links:
<a class="active" href="#section1">Link 1</a>
<a href="#section2">Link 2</a>
When a link 2 is clicked I would like it to receive the active class and remove the class from link 1 itself so it would effectively become:
<a href="#section1">Link 1</a>
<a class="active" href="#section2">Link 2</a>
This should work both ways. Ie. whatever link is clicked gets the class and removes it from the other.
How can this be done with JavaScript/Prototype?
Try this:
// 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(" ");
}
}
}
You could write a little helper function with prototype support that removes the class from all active
elements and adds it to the one that was clicked on:
function active(e) {
$$('.active').each(function(i) {
i.removeClassName('active');
});
e.addClassName('active');
};
You can than call this function from your onclick
events:
<a href="#sectiona" onclick="active(this)">a</a>
<a href="#sectionb" onclick="active(this)">b</a>
<a href="#sectionc" onclick="active(this)">c</a>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With