Set menu item active based on URL using Jquery

jQuery Comments Off on Set menu item active based on URL using Jquery

This is a small snippet using jquery that reads the current URL and set the corresponding menu item active by add a css class “active”. I have just given the html and jquery. You can design your own css.

HTML MENU

<div id=”cssmenu”>
<ul id=”menu”>
<li><a href=”/”><span>Home</span></a></li>
<li><a href=”products.aspx”><span>Products</span></a></li>
<li><a href=”services.aspx”><span>Services</span></a></li>
<li><a href=”about-us.aspx”><span>About Us</span></a></li>
<li><a href=”contact-us.aspx”><span>Contact Us</span></a></li>
</ul>
</div>

jquery to set css

 

<script src=”//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js”></script>

<script type=”text/javascript”>
$(document).ready(function () {
var str = location.href.toLowerCase();

$(“#menu li a”).each(function () {
if (str.indexOf(this.href.toLowerCase()) > -1) {

$(“li.active”).removeClass(“active”);

$(this).parent().addClass(“active”);

}

});

})

</script>

If you visit the url about-us.aspx then the menu item will be

<li class=”active”><a href=”about-us.aspx”><span>About Us</span></a></li>



Author

Search

Back to Top