If the URL ends: ?style=product
I want to add a class of active
to the li
with the class of product
HTML:
<
var style = '<?php echo $_GET['style'] ?>';
if(style == 'product'){
$('li.product').addClass('active');
}
use location.href to read the query parameters...
function getQuerystring(key, default_) {
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
var target = $("." + getQueryString("style", "default"));
function getStyleValue(uri)
{
var var, hash;
var hashes = uri.slice(uri.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
if(hash[0] == 'style')
{
return hash[2];
}
}
return false;
}
then you can use like
var selected = getStyleValue('index.php?style=product2') || "product";
$('a.' + selected).addClass('selected');
You could get the current url in jQuery like this:
$(location).attr('href');
Then cut off everything after '?' with a regex, to get yor current page
To add a class to the correct li-item:
$('li.'+style+').addClass('active');
First up you'll need a javascript function similar to the one posted here, this will allow you grab the style variable from the querystring.
Once you have that try something like:
var style = getParameterByName('style');
$('li.' + style).addClass('active');
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
.