I am just trying to retrofit an active state into a static html menu. The menu has the following structure: -
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');