1

Get query string

var queryString = window.location.search;

removes ? from beginning of query string

queryString = queryString.substring(1);

query string processor

var parseQueryString = function( queryString ) {
    var params = {}, queries, temp, i, l;
    // Split into key/value pairs
    queries = queryString.split("&");
    // Convert the array of strings into an object
    for ( i = 0, l = queries.length; i < l; i++ ) {
        temp = queries[i].split('=');
        params[temp[0]] = temp[1];
    }
    return params;
};

// query string object

var pageParams = parseQueryString(queryString);

// CSS variables

var target = pageParams.target;
var prop = pageParams.prop;
var value = pageParams.value;

// can't get to work -->

jQuery(target).css({
    prop : value,
});

I want to be able to supply a query like this one "?target=body&prop=display&value=none" and make the whole body disappear or target certain elements by their class.

2 Answers 2

2

You wouldn't be able to use prop as a key-variable for the object you're passing to .css(). In this case, it would translate to a literal string 'prop'. Instead, you'd have to do something like:

jQuery(target).css(prop,value);

Note: be careful about that trailing comma in that hash (after value). Some browsers will error at that point.

Sign up to request clarification or add additional context in comments.

Comments

0

In order to create a css object which you can pass to jQuery, I suggest something like this:

// Create css obj
var cssObj = {};
cssObj[prop] = value;

After this, the code works fine to me. See the full solution here:

http://jsfiddle.net/q97DH/4/

I recommend removing the question mark with a regex - see comment below.

4 Comments

The reason he is using substring is to remove the ?. For some reason I think that some browsers do not include the ?, so his method may not be the safest. Regardless, you should modify your regex (replace) so that it only removes question marks from the beginning of the string so that no subsequent question marks are removed: queryString.replace(/^\?/,'');
Jepp, I missed that line. I've edited the answer, thx for the hint :-)
About the regex: I agree, but I didn't use a regex. I just used replace. But still, question marks later in the string, maybe escaped, would be removed too, which could be critical. So let's be precise, I'll alter the fiddle.
Yeah :) I consider all replace to be regex. I might be wrong, but for some reason I thought that it uses regex under the hood, even when passing it a string as the match pattern. It's still not a bad idea to check if the first character is a question mark, since I still think some browsers include it, while others exclude it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.