Setting active tab or menu link of the current page using jquery

Javascript Comments Off on Setting active tab or menu link of the current page using jquery

Using jquery we can set the class of the tabs link or menu link to ‘active’ so we can highlight for the current page. the snippet is give below. It is achieved through jquery by iterating the links in the navigation bar or tabs and checking against the¬†window.location.pathname

<html>

<head>

<script src=”//code.jquery.com/jquery-1.9.0.js”></script>

<style type=”text/css”>

.active {font-weight:bold;}

</style>

<script>

$(document).ready(function () {
//iterate through the links and verify against window.location.pathname
var loc_href = window.location.pathname;
$(‘#nav a’).each(function () {
if (loc_href == $(this).attr(‘href’)) {
$(this).addClass(‘active’);
}
});
});

</script>

</head>

<body>

<ul id=”nav” class=”tabs”>
<li><a href=”/” title=”Home” class=”active”>Home</a></li>
<li><a href=”/about/”>Products</a></li>
<li><a href=”/demo/”>Services</a></li>
<li><a href=”/contact/”>Contact Us</a></li>
</ul>

</body>

</html>



Author

Search

Back to Top