Smith Foto
Smith Foto

Reputation: 159

How to do javascript add class active in LI navigation menu

I can not add class active in LI navigation menu where i click.

When i click on WHAT WE DO on home page it jump to what we do page so i need menu WHAT WE DO in what we do page to be active.

Here is my JSFIDDLE

JS

$( document ).ready(function() {        
  $( "#cssmenu a" ).click(function(e) {
  e.preventDefault();
  var navId = $(this).attr("href");
  var str = '.' + $(this).attr('id');
    $("html, body").animate({
      scrollTop: $(navId).offset().top
    }, 600);

    $(str).show();
    $(this).closest('ul').find('li').removeClass("active");
    $(str).find('li').removeClass("active");
    $(str).closest('ul').find('li').addClass("active");
  });
});

Upvotes: 1

Views: 1286

Answers (3)

Shaunak D
Shaunak D

Reputation: 20636

Updated Fiddle

You need to find li - a in what we do page to add the class.Change the last line to this,

$(str).find('ul li a#'+$(this).attr('id')).parent().addClass("active");

Or just

$(str).find('a#'+$(this).attr('id')).parent().addClass("active");

Note : Your markup has Duplicate IDs which is invalid.

Upvotes: 2

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

You are using same id for multiple elements. Please remove it and use different Ids for different elements.

You can add active class using below jQuery :

$(str).find('[href="'+navId+'"]').closest('li').addClass("active");

instead of

 $(str).closest('ul').find('li').addClass("active");

Working JSFiddle

Note : as active class has font color white hence it is not visible after adding active class to the li.

Upvotes: 2

k2fl
k2fl

Reputation: 11

Element IDs should be unique within the entire document.

Upvotes: 0

Related Questions