getButterfly
Resume

NAVIGATION

ATTRIBUTION

getButterfly
Dublin, Ireland

All Content Copyright ©2019
getButterfly

Cross-browser Query Parameter Getter and Setter

Here’s a cross-browser compatible way of getting query parameter from a URL or setting query parameters and reloading the page. An alternate way would be to fetch something based on the parameters and then push the parameters to history.

function getQueryParameters() {
    var queryString = location.search.slice(1),
        params = {};

    queryString.replace(/([^=]*)=([^&]*)&*/g, function (_, key, value) {
        params[key] = value;
    });

    return params;
}

function setQueryParameters(params) {
    var query = [],
        key,
        value;

    for (key in params) {
        if (!params.hasOwnProperty(key)) {
            continue;
        }
        value = params[key];
        query.push(key + "=" + value);
    }

    location.search = query.join("&");
}

The example below will show you how to use the functions. Let’s assume you want a <select&gt; dropdown to trigger an event, in our case a page reload.

document.getElementById('selector').addEventListener('change', function () {
    var params = getQueryParameters(),
        selectedParameter = this.value;

    params.my_parameter = selectedParameter;
    setQueryParameters(params);
});

And that’s it! You’ve done it!

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

Added by Ciprian on Saturday, September 29, 2018 in Blog, JavaScript

Do you want better SEO? More traffic? More conversions? More growth? We help companies exponentially grow their traffic and conversions, while outranking their competitors. With more than 10 years of experience, we’ve learned what is valuable to our clients.
SEO Dublin | SEO Malta

My Battle Tested Recommendations

Jetpack
Dreamhost
WordPress.com
CodeCanyon
SEMrush

Disclaimer: These recommendations contain affiliate links.


Privacy Policy