how can I append variables to an URL with javascript without navigating to the url ?
thanks
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With