Skip to content

How to Select active menu Item using jquery

activeitem

Most of the developer has an issue to select active menu in the same header. So here we try with the following example. May be this example will help you, If you have any doubt or question you can comment us. We will reply you ASAP.

<ul id="menu">
<li><a href="https://www.blogger.com/home">Home</a></li>
<li><a href="https://www.blogger.com/about">About us</a></li>
<li><a href="https://www.blogger.com/contact">Contact us</a>>/li>
</li>
</ul>

Suppos here we click on Home menu. Then home li should be selected. My URL is : http://www.example.com/home

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
  jQuery.noConflict();
  jQuery(document).ready(function() {
    var currentURL=location.href;
    var arrURL=currentURL.split("/");
    var currMenu=arrURL[3];
    if (currMenu != "") {
            jQuery('#menu li a').each(function(idx, item){
            var menuURL = jQuery(this).attr("href");
            if (menuURL == currMenu) {
                jQuery(this).addClass("active");
            }
        });
    }
 });
</script>
<ul id="menu">
<li><a class="active" href="https://www.blogger.com/home">Home</a></li>
<li><a href="https://www.blogger.com/about">About us</a></li>
<li><a href="https://www.blogger.com/contact">Contact us</a>>/li>
</li>
</ul>

 

Tags: