Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery add remove class

Tags:

jquery

class

add

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>
like image 778
mtwallet Avatar asked Feb 11 '10 16:02

mtwallet


People also ask

What does addClass do in jQuery?

jQuery addClass() Method The addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute. Tip: To add more than one class, separate the class names with spaces.

How do I add and remove a class from a scroll?

addClass('newClass'); } else { $('#dynamic'). removeClass('newClass'); } }); This allows you to add and/or remove classes after the user has scrolled down a certain amount in a page. In this case, fill background with orange after scrolling 50px down.

How do I delete a class?

The removeClass() method removes one or more class names from the selected elements. Note: If no parameter is specified, this method will remove ALL class names from the selected elements.


1 Answers

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");
});
like image 85
Sampson Avatar answered Sep 28 '22 04:09

Sampson