What I'm attempting to do:

I want to use jQuery to assign a class to an anchor tag when clicked, but remove classes from one to several other anchor tags on that same click

This is for a navigation element.

For example, before click:

HOME

Page 2

Page 3

Page 4

After click:

Home (Class removed)

PAGE 2 (Class added)

Page 3

Page 4

After another click:

Home

Page 2 (Class removed)

PAGE 3(Class added)

Page 4

I'm new to jQuery. I know how to assign classes on clicks, but I can't figure out how to remove classes to OTHER anchor tags on that same click.

I'm sorry if I can't articulate the issue properly, it's hard to explain. If you need me to try to elaborate further, please let me know. Thanks.

2 answers

3
points

You'll want to add a function to your click event. Within this function you can do all sorts of things, both related to the element that was interacted with and related to completely different elements. For example, in your case:

$("a.navigation").click(function() {
    $("a.navigation").removeClass("clickedClass");
    $(this).addClass("clickedClass");
});

Basically, when an element is clicked, you remove the class from all matching elements, then add it to this element, which selects only the element that you clicked. Hope this helps... let me know if I can be more specific. For reference, see:

http://api.jquery.com/click/

Answered over 6 years ago by Michael Martin-Smucker
0
points

I would go with Toggle. Use the toggle event handler and when clicked, grab the current navigation item, set the class, and loop though all other navigation items removing the class.

Click would also work, but in this case, I think toggle fits a little better.

http://api.jquery.com/toggle/

Answered over 6 years ago by Scott Radcliff
  • What is the benefit of using toggle over click in this case? As far as I know, the benefit of toggle is that you can give it a second function, which happens when the item is clicked a second time, but I don't see how that would be useful here. Michael Martin-Smucker about 6 years ago