fancy
fancy

Reputation: 51443

Use anchors/hashbangs in the URL to trigger functions on load?

Say someone is linked to the url, example.com/#boom

Can the hashbang in the url, #boom be linked to triggering a function like boom() on the page?

Thanks!

Upvotes: 0

Views: 1384

Answers (4)

Floern
Floern

Reputation: 33904

Maybe something like this:

window.onload = function(){ // Page onload
    if(location.hash == "#boom"){ // Hash is "boom"
        boom(); // call function boom()
    }
}

Upvotes: 0

ShaneC
ShaneC

Reputation: 2406

Easily done with JavaScript:

if( window.location.hash ){
    var currentHash = window.location.hash;
    alert( "Yup! " + currentHash + " is set." );
}else{
    alert( "Nope!" );   
}

Now this is an example. Obviously you would want to call your call back function instead of outputting currentHash.

For more information on calling the function: http://w3future.com/html/stories/callbacks.xml

Upvotes: 0

Digital Plane
Digital Plane

Reputation: 38264

I think you want to do something like this:

window.onload = function(){
  var hash = location.hash.substr(1);
  if(typeof window[hash] == "function")
    window[hash]();
};

If the function specified in the hash exists, then it will be called on page load.

Upvotes: 4

ChrisJ
ChrisJ

Reputation: 5251

Not sure to understand what you really want... On your web page, you can add code that runs at page load, that examines the URL and that calls a suitable function accordingly. You will want to use window.location for this.

Upvotes: 1

Related Questions