I have a set of tabs in html which I want to highlight when selected. I am trying to use jquery to do this. But it does not seem to work.
$(function () {
setNavigation();
});
function setNavigation() {
var path = window.location.pathname;
path = path.replace(/\/$/, "");
path = decodeURIComponent(path);
$(".nav a").each(function () {
var href = $(this).attr('href');
if (path.substring(0, href.length) === href) {
$(this).closest('li').addClass('active');
}
});
}
a {
color:#000;
text-decoration:none;
}
a:hover {
text-decoration:underline;
}
a:visited {
color:#000;
}
.nav {
padding:10px;
border:solid 1px #c0c0c0;
border-radius:5px;
float:left;
}
.nav li {
list-style-type:none;
float:left;
margin:0 10px;
}
.nav li a {
text-align:center;
width:55px;
float:left;
}
.nav li.active {
background-color:green;
}
.nav li.active a {
color:#fff;
font-weight:bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul class="nav">
<li><a href="#tab1">tab1</a>
</li>
<li>|</li>
<li><a href="#tab2">tab2</a>
</li>
<li>|</li>
<li><a href="#tab3">tab3</a>
</li>
<li>|</li>
<li><a href="#tab4">tab4</a>
</li>
</ul>
That is doable with a on click event:
$(document).on("click", 'ul li', function(){
$('ul li').removeClass('active');
$(this).addClass('active');
});
a {
color:#000;
text-decoration:none;
}
a:hover {
text-decoration:underline;
}
a:visited {
color:#000;
}
.nav {
padding:10px;
border:solid 1px #c0c0c0;
border-radius:5px;
float:left;
}
.nav li {
list-style-type:none;
float:left;
margin:0 10px;
}
.nav li a {
text-align:center;
width:55px;
float:left;
}
.nav li.active {
background-color:green;
}
.nav li.active a {
color:#fff;
font-weight:bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul class="nav">
<li><a href="#tab1">tab1</a>
</li>
<li>|</li>
<li><a href="#tab2">tab2</a>
</li>
<li>|</li>
<li><a href="#tab3">tab3</a>
</li>
<li>|</li>
<li><a href="#tab4">tab4</a>
</li>
</ul>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With