I am just trying to retrofit an active state into a static html menu. The menu has the following structure: -
Checkout the fiddle here : http://jsfiddle.net/EVmsY/
$(function(){
var url = 'http://www.thesite.com/product1.htm'; // window.location;
var page = url.substr(url.lastIndexOf('/') + 1);
if (page) {
$('#MenuBar1 li a[href="' + page + '"]').addClass('active');
$('.active').parents().children('li a').addClass('active');
}
});
You can get the current path with JavaScript using window.location.pathname
. You can check with jQuery using something like:
$("#navbar a[href=" + window.location.pathname + "]").addClass('active');
This will add the active
class to all anchors in #navbar
that have the same href
attribute as the current path. You may need to trim the leading slash.
use window.location.href
to get the current current URL location of the browser... and addClass()
to add a classname to the link... inmycase i am adding active
try this
<script>
$(function(){
var currenthref=window.location.href;
$("#navbar a[href=" + currenthref + "]").addClass('active'); //adds active class to the current url.
})
</script>
You could do something like this:
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
$('#MenuBar1 a').each(function() {
if(filename == $(this).attr('href')) {
$(this).addClass('active');
}
});
If you need the class applied to the li do something like this:
var url = window.location.pathname; var filename = url.substring(url.lastIndexOf('/')+1);
$('#MenuBar1 a').each(function() {
if(filename == $(this).attr('href')) {
$(this).parent('li').addClass('active');
}
});
The above responses will come out incorrect because they will give the full pathname so if your url is like this:
http://www.thesite.com/about.htm
The "window.location.pathname" is going to return this:
/about.htm
So you would need to do something like this in order to leave the markup the way you have it and get the desired result or you could just prepend slashes to the front of the href.
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
$("#navbar a[href=" + filename + "]").addClass('active');