0
<ul class="nav">
    <li>
        <a href="/dashboard">
            <i class="material-icons">dashboard</i>
            <p>Dashboard</p>
        </a>
    </li>
    <li>
        <a href="profile">
            <p>User Profile</p>
        </a>
    </li>
</ul>

Now what i want is if i click on one of this it will become active so what i did is-

   $(document).ready(function() {
  $('li').bind('click', function() {
    $( this ).addClass('active');
  });
});

but the problem is it has no applied class after loading the page so i want it applid after loading the page i also tried toggleClass

$('li').on('click', function() {
  $(this).parent().toggleClass('active'); 
});

any Suggestoins.. thank you..

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Kalariya_M
  • 1,357
  • 12
  • 20

2 Answers2

1

1.Highlighting <a> based on current page:-

$(document).ready(function(){
   var url = location.pathname;// Returns path
   $('.nav li a').each(function(){
     if(url.indexOf($(this).attr('href'))!== -1){
       $(this).addClass('active'); 
     }
   }
});

2.OR Highlighting <li> based on current page:-

$(document).ready(function(){
   var url = location.pathname;// Returns path
   $('.nav li a').each(function(){
     if(url.indexOf($(this).attr('href'))!== -1){
      $(this).closest('li').addClass('active');
     }
   }
});
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
0

I can realize that you are looking for something like this: Adding active based on URL

First of all you need to define an .active css class, something like this:

.active{
    color:red;
}

then call your js when the page is ready:

 $(document).ready(function() {
  $('li').on('click', function() {
    $( this ).toggleClass('active');
  });
});

Instead of putting changes to li parent put it on li, because you want to toggle class for that itself.

Example: https://jsfiddle.net/qcsw2kcd/1/

bhansa
  • 7,282
  • 3
  • 30
  • 55