I won’t give you a kiss, just think a little, but follow an example of how to do:
Before:
html:
<header>
<ul class="nav">
<li><a href="#home">Home</a>
</li>
<li>|</li>
<li><a href="#tour">Tour</a>
</li>
<li>|</li>
<li><a href="#about">About</a>
</li>
<li>|</li>
<li><a href="#contact">Contact</a>
</li>
</ul>
</header>
JS:
$(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');
}
});
}
CSS:
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;
}
Link in jsfiddle
Each page load this script runs and compares the href of each menu link to the current page URL.
Note that the jsFiddle example won’t work because you can’t really change the URL in the results window, but you can easily copy the code to an HTML file to test it.
Afterward:
Can you post your full code? your html with menus and content.
– Fernando Leal
This is the HTML friend. It’s inside a loop. That is, this
div
that I posted above, repeated five times.– Felipe Viero Goulart