If the URL ends: ?style=product
I want to add a class of active
to the li
with the class of product
HTML:
<
You should probably go with Andy and render this serverside, but to answer your question, this is what you should do to achieve the same in javascript/jQuery (if, say, there is no server-side)
There are definitely easier ways of getting the 'style' querystring, if you can make a lot of assumptions about the url (that it will always have that querystring, that it will always be the first querystring, that there will never be any other querystrings, that there will never be any hash data after the querystring...). The below is probably the safest way to go if you cannot make such assumptions.
var activeStyle = '';
if(window.location.search != '') {
// find querystring section or url
var query = window.location.search.substring(1);
// split querystring into key/value-pairs
query = query.split('&');
for(var i = 0; i < query.length; i++) {
// split key/value pair into key and value
var keyvalue = query[i].split('=');
// find value of ?style=
if(keyvalue[0].toLowerCase() == 'style')) {
activeStyle = keyvalue[1];
break;
}
}
}
if(activeStyle != '') {
$('li.' + activeStyle).addClass('active');
}
Note that I assumed that you also want product2
to become active
in case your URL ends in style=product2
. If you only want to apply this effect when product
is selected, you would have to adjust the last condition to
if(activeStyle.toLowerCase() == 'product') {
$('li.product').addClass('active');
}
EDIT
Edited the above selection to use window.location.search
instead, to pick up on Andy's advice, which guards against location.hash
.