I saw some of websites executes a JavaScript function based on has in the URL. For example,
when I access http://domain.com/jobs#test
then the website executes a function based on #test
I can do it by checking location.href, but is there a better way?
Yes, it can contain executable code (of any kind, including javascript) since URL is a plain string data.
The hash of a url can be found by creating a new URL Javascript object from the URL string, and then using its hash property to get the value of the hash fragment. Note that this will include the # character also. If the url does not contains a hash, then an empty string "" will be returned.
To call JavaScript function from URL or address bar, we can type in a data URL. into the address bar to run the JavaScript code in the script tag. Therefore, we see an alert box that shows 'hi' displayed when we type this in.
This is what i do:
window.onload = function(){
var hash = (window.location.hash).replace('#', '');
if (hash.length == 0) {
//no hash do something
}
else {
//else do something with hash
}
}
demo: http://jsfiddle.net/maniator/XCjpy/show/#test
demo2: http://jsfiddle.net/maniator/XCjpy/show/
demo3: http://jsfiddle.net/maniator/XCjpy/show/#testing_again
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