Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: how can I append variables to the url?

Tags:

javascript

how can I append variables to an URL with javascript without navigating to the url ?

thanks

like image 902
aneuryzm Avatar asked Dec 17 '25 18:12

aneuryzm


1 Answers

To append variables to the hash (as Matthew suggested), you can do the following in plain JavaScript:

window.location.hash = 'varA=some_value;varB=some_value';

This will add #varA=some_value;varB=some_value to your URL. It will not refresh the page unless the hash value is equal to an anchor name or an element id within the document.

Then to check if a hash value is present, simply do the following:

var i, variables = window.location.hash.split(';');

if (variables.length > 0) {
    // Variables present in hash
    for (i = 0; i < variables.length; i++) {
       keyValuePair = variables.split('=');
       // keyValuePair[0] would be the key (variable name)
       // keyValuePair[1] would be the value
    }
}
else {
    // No variables in the hash
}

You may also want to check out the following Stack Overflow post on issues related to the URL encoding of the hash part in different browsers:

  • Encoding of window.location.hash
like image 91
Daniel Vassallo Avatar answered Dec 20 '25 07:12

Daniel Vassallo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!