Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Add Class When Link is Clicked

Tags:

javascript

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?

like image 842
a1anm Avatar asked Jan 10 '10 15:01

a1anm


2 Answers

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(" ");
        }
    }
}
like image 123
Gumbo Avatar answered Oct 30 '22 11:10

Gumbo


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>
like image 24
Josef Pfleger Avatar answered Oct 30 '22 11:10

Josef Pfleger