None
None

Reputation: 9247

How to set active link in jquery?

I'm trying to set active link when user clik on it but i cant figureout how to remove last clicked. This is my fiddle:

http://jsfiddle.net/9ff79/222/

 $(function() {
  $( 'nav ul li a' ).on( 'click', function() {
        $(this).parent().find( 'nav ul li a .active' ).removeClass('active');
        $(this).addClass('active');
  });

});

Upvotes: 2

Views: 2204

Answers (3)

Salmin Skenderovic
Salmin Skenderovic

Reputation: 1720

Unless you have more nav-elements you a and .active. That is implying you have a child element with the class active.

Try this:

$( 'nav ul li a.active' ).removeClass('active');

Upvotes: 0

lharby
lharby

Reputation: 3265

This is how I got there:

$(function() {
      $('nav ul li a').on('click', function() {
            $('nav ul li a').removeClass('active'); // remove active class from ALL href's
            $(this).addClass('active'); // add active class for the element clicked
      });
});

http://jsfiddle.net/lharby/9ff79/223/

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337560

Your DOM traversal from the clicked a element isn't correct. Use closest() then find() to get the current .active element:

$('nav ul li a').on('click', function () {
    $(this).closest('nav ul').find('a.active').removeClass('active');
    $(this).addClass('active');
});

Updated fiddle

Upvotes: 1

Related Questions