webmonkey237 webmonkey237 - 1 year ago 87
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:


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('&'),

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')) {
} else {

if($(border == 'yes')) {
} else {


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.



Answer Source

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');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download