Reputation: 792
I have a tab (bootstrap <ul>
). I want to highlight the color of sected item by jquery.
here is my html
<ul class="nav navbar-nav">
<li class="active"><a href="index.html">Home</a></li>
<li id="aboutus">@Html.ActionLink("About Us", "aboutus","home")</li>
<li id="service">@Html.ActionLink("Services", "Services", "home")</li>
<li id="portfolio">@Html.ActionLink("Portfolio", "portfolio", "home")</li>
</ul>
my question is how do I change the color of the item, which is selected by user?
Upvotes: 1
Views: 142
Reputation: 5175
The problem is that every time you navigate to a different page and the navbar gets refreshed it will always select the first <li>
as active. Using jQuery you can get the url of the current page and see which one of the links has this address as href and add the active class to it. Remove the active link from the first item in the dropdown and use jQuery to add the active class.
Markup
<ul class="nav navbar-nav">
<li><a href="index.html">Home</a></li>
<li id="aboutus">@Html.ActionLink("About Us", "aboutus","home")</li>
<li id="service">@Html.ActionLink("Services", "Services", "home")</li>
<li id="portfolio">@Html.ActionLink("Portfolio", "portfolio", "home")</li>
</ul>
jQuery
<script>
$(document).ready(function () {
var activeLink = location.pathname.substr(location.pathname.lastIndexOf('/'), location.pathname.length);
var parent = $('a[href$="' + activeLink + '"]').parent('li');
if (parent.closest('ul').hasClass('dropdown-menu')) {
parent.parents('.dropdown').addClass('active');
}
parent.parent('li').addClass('active');
});
</script>
This extra <ul>
checks are used if the navbar have dropdowns with more links inside of it.
Upvotes: 1