0

I want to use javascript or jquery to add a class to an object based on the URL query string.

So if the url is example.com/?var=1 then I want to add a new class to the object #mydiv

This would then be repeated for ?var=2, ?var=3 and so on.

Here is what I have tried. The hope for this is that it would add a different class to the object if the query string was either ?var=2 or?var=3

var queryString = window.location.search.substr(1); 

switch (queryString) {
    case "2": document.getElementById('mydiv').className = 'newclass2';
;
                   break;
    case "3": document.getElementById('mydiv').className = 'newclass2';
;
                     break;
  }

EDIT:

It almost works now....

Here is my current code:

<script>
 var queryString = window.location.search.substr(1);
 var variant = queryString.split('=')[1];
 switch(variant) {
    case "stnl2": document.getElementById('getexclusive-sb').className = 'stnlvar2';
;
break;
    case "stnl3": document.getElementById('getexclusive-sb').className = 'stnlvar3';
;
break;
  }
</script>

It works if the url is "/?v=stnl2"

However Google content adds more to the url such as "?v=stnl2&utm_expid=42387987-0.dmsadhasjkdjasgdjgas-Q.4"

Is there a way for me to ignore the & and all details after so my code still works?

Parks
  • 21
  • 5

2 Answers2

0

The solution you tried has two issues.

First, you are getting the number of variant incorrectly. With your code, queryString will be like "var=2". So if you want only number, you should also split it by =:

 var queryString = window.location.search.substr(1);
 var variant = queryString.split('=')[1];
 switch(variant) {
     // ...
 }

Note that this still actually doesn't check the name of your parameter, i.e. var=. If it is the only parameter, it would work. Otherwise, for proper handling of query string in JS you might want to look at this question

Second, look attentively into your switch. Both branches are actually identical, so they would do exactly the same regardless of queryString. Seems like you copy-pasted it unintentionally.

UPD:

As a said in my original answer, I just pointed you to some issues in your solution and how to fix them. It would not work if there is more than one parameter. Of course, you can just ignore all the string after &. But still there would be many cases in which it still won't work: what if your parameter is not the first?

I think it is not a good idea to make such assumptions, so we come to what I said previously: you might need proper, full-fledged parsing of parameters. The link that I mentioned provides A LOT of solutions for this particular task, you may choose any of them. Another option is to use some existing library which have such function provided. That question and some other SO questions pointed me to these two:

  • jquery.parsequery — a jQuery plugin for this only purpose, with which you can do variant = $.query(location).get("paramName"). Seems to be old and not updated.
  • jsurl — a library for making different things with URLs, in particular, you can do variant = (new Url).query.paramName with it.

NB: (replace paramName with your actual parameter name, v or var or whatever)

Of course there could be some other good libs for it, also try googling on your own.

Community
  • 1
  • 1
NIA
  • 2,523
  • 22
  • 32
  • Thank you. The name isn't too important as I am just trying to style different variations for a Google experiement. So now it almost works but... – Parks Oct 15 '13 at 11:57
  • Ok, I added more to the above question. Thanks for your help so far, it's almost working. – Parks Oct 15 '13 at 11:59
  • @ForestParks That is what I meant by saying that it would work only if there is only one parameter. Follow the link in my answer to a SO question which offers LOTS of various solutions for getting the parameter from query string by its name. I also updated my answer and added some more links. – NIA Oct 15 '13 at 12:38
  • Thanks. I am fairly new to javascript so honestly having real trouble wrapping my head around it... Still trying though. – Parks Oct 15 '13 at 13:05
  • In this case my "v=stnlvar2" or whatever will always be the first parameter because the Google experiment is set up to redirect to these variations and then it adds it's own stuff after the &... So is there an easy way for now to ignore the & and everything after? – Parks Oct 15 '13 at 13:07
  • @ForestParks Well you may do it just like you did with `=`: split by & and get first part, something like `queryString.split('&')[0]`. But I strongly discourage from using this, because correct URLs would still break your logic, and this may cause a lot of pain in later debugging. Do look the links I provided, there are the simple solutions as well there. – NIA Oct 15 '13 at 13:38
  • Thanks for your help here. The answer from Harry seemed to do everything you suggested such as pull out the specific name and not rely on it being in a certain order either. – Parks Oct 15 '13 at 15:05
0
var getUrlVars = function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++){
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    if(vars[0] == window.location.href){
        vars =[];
    }
    return vars;
}
var params = getUrlVars();
switch (params['var']){
...
}

Your params will have all the parameters from your query string. just past the variable name as a string and you will get the value of that parameter.

Harry Bomrah
  • 1,658
  • 1
  • 11
  • 14
  • That's working for me now. Thank you.... I am guessing this only works if the var parameter appears first in the URL? – Parks Oct 15 '13 at 13:47
  • No it can work for anything .. for ex if ur parameter name is abc then u ve to get params['abc'] .. this will give u value of abc parameter. – Harry Bomrah Oct 15 '13 at 14:16