Question

It is possible if i have more links with the same class, on click add aditional class for active item? I have tried with jquery '.toggleClass()' but if i click on next link then both links has the same class

<a href="link1.html">1</a>
<a href="link2.html">2</a>
<a href="link3.html">3</a>

I have tried:

$('a').click(function() { 
    $('a').toggleClass('active'); 
});
Was it helpful?

Solution 2

I don't see any class in your html, but I add some for a example. Try this:

html

<div class="menu">
<a href="link1.html">1</a>
<a href="link2.html">2</a>
<a href="link3.html">3</a>
</div>

jQuery

$('.menu a').click(function(){ //check thru all <a> elements  inside .menu
    $('.menu ').removeClass("active"); // remove all active class    
    $(this).addClass("active"); //put active in parent of <a> which was clicked
});

OTHER TIPS

You need to use this:

$('a').on('click', function(e) {
  e.preventDefault();
  $(this).toggleClass('active').siblings('a.active').removeClass('active');
});

So, when an anchor is clicked, toggle the active class on that given anchor, and remove the active class from all siblings which are anchors and have the active class.

Here's a fiddle

Use the addClass() method

$('.link').addClass('active');

Check this:

Demo: http://jsfiddle.net/RKjh7/1/

$('a').click(function(){
   $(this).addClass('yourClass');
});

Upon clicking on one of the links, remove the active class from current link, and add to the link just clicked.

    $('a').click(function()
    {
       $('.active').removeClass('active');
       $(this).addClass('active');
    });

First remove the active class from all link and then add it on the clicked element.

Try this :

jQuery('.link').click(function(e){
   e.preventDefault();
    var elem = jQuery(this);
    jQuery('.link').removeClass('active');
    elem.addClass('active');

});

Here is the demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top