webmonkey237 webmonkey237 - 3 months ago 6
jQuery Question

jQuery: Getting a value from URL to add a class

I'm a beginner so be gentle, I have found a script that pulls down information from the URL so for example my URL looks like:

http://www.website.com/page/pagename?circle=yes&border=no


What I am trying to achieve is:
If "circle" equals "yes" then addClass

Please see my code below:

$(document).ready(function () {

var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;

for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');

if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};

var circle = getUrlParameter('circle');
var border = getUrlParameter('border');

if($(circle == 'yes')) {
$(".testDiv").addClass("circ")
} else {
$(".testDiv").removeClass("circ")
};

if($(border == 'yes')) {
$(".testDiv").addClass("bdr")
} else {
$(".testDiv").removeClass("bdr")
};

});


It's the last part im stuck on, I have got the var for "circle" and "border" but the result could be "yes" or "no" so my thinking is if "circle" equals "yes" add the class else remove the class if it exists.

At the moment it just adds the class regardless on whether the result is yes or no, even if both are set to no.

http://www.website.com/page/pagename?circle=no&border=no


Thanks

Answer

So one of your problems right off the bat is that your if statement doesn't have the right syntax

if($(circle == 'yes')) // what you have
if(circle === 'yes') // what you should have

However you could streamline this by using toggleClass().

$(".testDiv").toggleClass('circ', circle === 'yes');
$(".testDiv").toggleClass('bdr', border === 'yes');
Comments