COS
COS

Reputation: 553

jquery <li> on click navigate to url and add class after

I'm trying to add a class to a li element when clicking the link inside and also navigate to that url, but the class disappears after page is loaded. So how can i add the class after the page is loaded?

<ul>
<li class="tab"><a href="./my_page.html" class="li-trigger">My Page</a></li>
<li class="tab"><a href="./some_page.html">Some Page</a></li>
<li class="tab active"><a href="./some_page2.html">Another Page</a></li>
</ul>


<script type="text/javascript">
    jQuery(document).ready(function(){  
        jQuery('.li-trigger').click(function (event){
            jQuery(this).parent('li').addClass('active').siblings().removeClass('active');
        });
    }); 
</script>

Upvotes: 0

Views: 1434

Answers (3)

charlietfl
charlietfl

Reputation: 171679

You need to do this when the page loads, not in a click handler. Iterate the links and compare the href to the current page url

$(function(){
  var pageUrl = location.href;
  $('.tab a').each(function(){
     $(this).parent().toggleClass('active', this.href === pageUrl);
  });
})

Upvotes: 2

Bad Hombre
Bad Hombre

Reputation: 594

jQuery

$(document).ready(function(){
  var path = window.location.pathname;
  $('.li-trigger[href="'+path+'"]').parent('li').addClass('active').siblings().removeClass('active');
});

This finds the .li-trigger's href and adds active class to correspondingly

Upvotes: 1

mehulmpt
mehulmpt

Reputation: 16547

Your webpage doesn't remember things. However, you can create a memory using localStorage that the user clicked the button.

jQuery(document).ready(function(){  
        
        jQuery('.li-trigger').click(function (event){
            jQuery(this).parent('li').addClass('active').siblings().removeClass('active');
            localStorage.setItem('clicked', 'yes');
        });

        if(localStorage.getItem('clicked')) {
          jQuery('.li-trigger').click();
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<ul>
<li class="tab"><a href="./my_page.html" class="li-trigger">My Page</a></li>
<li class="tab"><a href="./some_page.html" class="li-trigger">Some Page</a></li>
<li class="tab active"><a href="./some_page2.html" class="li-trigger">Another Page</a></li>
</ul>

(The code doesn't work with stacksnippets, try in live production)

Upvotes: 0

Related Questions