jquery add remove class

mtwallet picture mtwallet · Feb 11, 2010 · Viewed 36k times · Source

I have 4 anchors, I want to add a class of current to an anchor as it is clicked and remove the class from the other 3 at the same time. Here's my code. what am I doing wrong?

if ($("ul#thumb a").hasClass("current") {
    $("ul#thumb a").removeClass("current");
    $(this).addClass("current");
});

and my html looks like this:

<ul id="thumbs">
    <li>
        <!-- intro page navi button -->
        <a id="t0" class="active" name="t0">The Company</a>

        <ul class="navi">
            <li><a style="display:none"></a></li>
            <li><a id="t1" name="t1">The Brief</a></li>
            <li><a id="t2" name="t2">The Solution</a></li>
            <li><a id="t3" name="t3">The Result</a></li>
        </ul>

    </li>
</ul>

Answer

Sampson picture Sampson · Feb 11, 2010

By using event-delegation, we only bind one handler for all click events. When an anchor (other than the .current anchor) is clicked, we strip the .current anchor of its class, and make the clicked anchor the new current one:

$("#thumbs").on("click", "a:not(.current)", function ( event ) {
    $(".current", event.delegateTarget).removeClass("current");
    $(this).addClass("current");
});