Auto select menu using jQuery

Hello guys, today we’ll learn about How we can auto select menu using Jquery.

The most common functionality in almost all websites is that to show selected menu which was previously clicked. There are many ways to do this, either we can achieve this using server side language or we can use jQuery or javascript(Almost all browsers supports javascript by default). So its up to us, how we want to integrate this.

I will use jQuery  and almost each website use this for having image slider, hierarchical dropdown etc which not possible without using jQuery.

So let’s start doing code, before coding let’s think, how we can do this.

The Idea, I am using is very simple, what I will do, I will get the page name from the browser URL and compare with each menu. isn’t simple?

On page load I will call one function that will get page name from URL and one by one it will compare that page name with each menu and if menu matches with page name then we can add class that is responsible to add styles to make menu look like selected, following is the code that will auto select the menu item.

 $(function () {

            var url = document.location.href;
            var page = url.substring(url.lastIndexOf('/') + 1).toLowerCase();
            
            $(".left-navigation li").each(function () {

                var href = $(this).find("a").attr("href");
                var menuUrl = href.substring(href.lastIndexOf('/') + 1).toLowerCase();
            
                if (page == menuUrl) {
                    $(this).addClass('active');
                }

            });
            
        });

Leave a Reply