JavaScript Add Class When Link is Clicked

javascript

Solution

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>

Problem

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?

Original source