Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery addclass/removeclass on click

Tags:

html

jquery

I'm trying to add a class [active] when I click on a element in my menu. Then remove that class [active] when I click on a new item in the menu and add the [active] class to it.

I've tried $(this).removeClass("active").addClass("active");

$(this).toggleClass("active");

Basically i'm trying to make the hover() function but with the click even.

Edit: Fixed HTML

<ul class="menu">
    <li><span>Three</li>
    <li><span>Two</li>
    <li><span>One</li>
</ul>
like image 737
Edward Avatar asked Nov 08 '12 19:11

Edward


People also ask

What is addClass and removeClass in jQuery?

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 a class to click?

To add a class on click of anchor tag, we use addClass() method. The addClass() method is used to add more property to each selected element. It can also be used to change the property of the selected element.


1 Answers

Assuming only one active element at a time and without further knowledge of your DOM hierarchy.

$('.active').removeClass('active');
$(this).addClass('active');

More efficient options are available if the DOM hierarchy is known.

For example, if they're all siblings, you can use this:

$(this).addClass('active').siblings('.active').removeClass('active');
like image 145
Alnitak Avatar answered Sep 23 '22 23:09

Alnitak