I want to be able to determine what page the user is currently on. a simple indicator in the form of adding unique style to the navigation link the user is currently viewing its context
here is my script, all selectors working fine, if statement also do the job, but the addClass() function does nothing.. here is my code:
<script>
$(document).ready(function(){
var pathname = window.location.pathname;
$("#links ul li a").each( function() {
var href= $(this).attr("href");
if (pathname.indexOf(href) >= 0){
$(this).addClass("active");
}
} );
});
</script>
<nav id="links">
<ul>
<li><a href="index.php">Home</a></li>
<li><a>About</a></li>
<li><a>Contact</a></li>
</ul>
</nav>
HTML :
got it to work ,this is my finaly code, is there a need for any improvments ?
$(document).ready(function(){
var pathname = window.location.pathname;
var onDomain=true;
$("#links ul li a").each( function() {
var href= $(this).attr("href");
if (href != undefined && pathname.indexOf(href) >= 0){
$(this).addClass("active");
onDomain=false;
}
});
if (onDomain){
$("#links ul li:first-child a").addClass("active");
}
});
Assign href
to a
;
<nav id="links">
<ul>
<li><a href="index.php">Home</a></li>
<li><a href="">About</a></li>
<li><a href="">Contact</a></li>
</ul>
</nav>
Then try:
var pathname = window.location.pathname;
$("#links ul li a").each( function() {
var href= $(this).attr("href");
if (href.length && pathname.indexOf(href) >= 0){
$(this).addClass("active");
}
});
If you can't change the HTML then try like following:
var pathname = window.location.pathname;
$("#links ul li a").each( function() {
var href= $(this).attr("href");
if (href != undefined && pathname.indexOf(href) >= 0){
$(this).addClass("active");
}
});
It is probably that the active class should be applied to the li.. Assuming your logic is correct and the class should be applied to the li (hard to tell without the html and css):
if (pathname.indexOf(href) >= 0){
$(this).parent().addClass("active");
}
var loc = ''+( $(location).attr('href').split('/').slice(-1) );
if( typeof loc !== 'undefined'){
$("#links li").find("a[href='"+loc+"']").each(function(){
$(this).addClass("active");
});
}else( typeof loc === 'undefined' ){
$("#links li a:eq(0)").addClass("active"); // if you use 'home' as your first.
}
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