JavaScript

How to Select active menu Item using jquery

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>

 

Developer Diary

Share
Published by
Developer Diary
Tags: JQuery

Recent Posts

Git Tag Cheat Sheet

Introduction Git tags are an essential feature of version control systems, offering a simple way…

2 months ago

Understanding Web Storage: Cookies, Local Storage

Introduction The methods that browsers employ to store data on a user's device are referred…

3 months ago

Setting up OpenVPN Access Server in Amazon VPC – AWS

Introduction A well-known open-source VPN technology, OpenVPN provides strong protection for both people and businesses.…

3 months ago

Enhance Error Tracking & Monitoring: Integrate Sentry with Node.js & Express.js

Introduction Integrating Sentry into a Node.js, Express.js, and MongoDB backend project significantly enhances error tracking…

3 months ago

Comparing Callbacks, Promises, and Async/Await in JavaScript

Introduction In the world of JavaScript development, efficiently managing asynchronous operations is essential. Asynchronous programming…

5 months ago

How To Secure Nginx with Let’s Encrypt on Ubuntu EC2 Instance

Introduction Let's Encrypt is a Certificate Authority (CA) that makes it simple to obtain and…

7 months ago