How to add an active class in navigation menu item in asp.net website?

Generally active class show which page /link you are visiting currently. Active class will be added in CSS class, but the problem is only one item can have active class at one time. But we need to show active class dynamically.

Add an active class in menu item in ASP.NET website?

In asp.net generally we work with master page and common menu items. So we need dynamic way to apply active class on menu item.
So do you think to solve this issue C# coding is worth? Better option is to do with java script and a jQuery min library file.

To do this first create an active class in css file:

.active
{
       line-height:37px;color:#FFF;
       font-size:14px;
       font-weight:bold;
}

And put below java script code in master page.

<script>
            $(function () {
                var pgurl = window.location.href.substr(window.location.href.lastIndexOf(“/”) + 1);
                $(“.menu ul li a”).each(function () {
                    if ($(this).attr(“href”) == pgurl || $(this).attr(“href”) == )
                        $(this).addClass(“active”);
                })
            });
        </script>

If you face any issue, put an alert and check the value you are getting and then manipulate the code as per your need.

Don’t forget to link jquery.min.js or any other jQuery min file, which you can get easily.

Please like us on FB if this article is helpful for you.

Leave a Comment

RSS
YouTube
YouTube
Instagram