I’d like to update my navigation styles on page load by adding classes grabbed from the URL path. However, my code is throwing an error which I can’t work out.
My URL looks like this as I’m loading pages via ajax.
Im creating an array using the following:
var hashpath = window.location.hash.substring(1).split( '/' );
Then I’m using jQuery.each to loop through the array and add a class:
jQuery.each(hashpath, function(i, val) {
urlclass = val.toString(); // tried converting to string just in case
// alert(urlclass);
// var className = "articles"; // if I use this in the selector below the class is add Ok.
$('#menu-main li.' + urlclass + ' a').addClass('current');
});
I would expect the element with the selector ‘a.articles’ to have the class ‘current’ added.
However, this is throwing an error as if it can’t see the variable passed in:
Uncaught Error: Syntax error, unrecognized expression: #menu-main li. a
Well that helped! I stripped down the page and it focused my mind on what was happening.
I think it was that the ‘/’ on the beginning of the url (although there is one on the end too) that was stored as an empty variable which was running first and throwing and error.
Good news!
It is amazing how making a bare-bones example that others can reproduce can focus your mind on the task in hand and more often than not lead to you solving your own problem.