Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a js function based on url hash url#nameoffunction

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?

like image 298
Moon Avatar asked May 20 '11 19:05

Moon


People also ask

Can you embed JavaScript in URL?

Yes, it can contain executable code (of any kind, including javascript) since URL is a plain string data.

How do I add a hash to a URL?

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.

How run JavaScript in browser address bar?

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.


1 Answers

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

like image 71
Naftali Avatar answered Nov 15 '22 16:11

Naftali