9

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?

1
  • You asked right question friend (y) Commented Feb 27, 2014 at 6:29

5 Answers 5

10

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

Sign up to request clarification or add additional context in comments.

1 Comment

You saved me friend (y)
3

If you don't need to support old browsers like IE6 and IE7 you can use:

window.onhashchange = function(){
  switch(location.hash) {
    case '#hash1':
      //do something
    break;
    case '#has2':
      //do something else
    break;
  }
}

But if you have to support older browsers you need to poll:

var oldHash = location.hash;
setInterval(function(){
  if(location.hash !== oldHash){
    oldHash = location.hash;
    //hash changed do something
  }
}, 120);

2 Comments

// Thank you for the input. I didn't know there is such event, but..what I want to do is execute a function upon onload or domready by checking hash tag. I tested it out, but onhashchange doesn't fire when i access a url with hash tag attached. I appreciate your input though.
What you could do is set a function hashChanged that you use for window.onhashchange = hashChanged. And you call the same function hashChanged() in a script tag at the very end of the body tag
2

Live Demo

$(window).bind('hashchange', function() {
    var hash = document.location.hash;
    var func = hash.replace('#', '');
    eval(func + '()');
});

function asdf() {
    alert('asdf function');
}

function qwerty() {
    alert('qwerty function');
}

Note: eval() is dangerous. You should make a predefined array of safe functions, and call those.

1 Comment

Put an eval in the answer, and then tell not to use it? Nice :)
1

Have a look at This.
See the property table.
location.hash should help you.

Comments

0

You could use a library like YUI to do this more elegantly, Take a look at the YUI Browser History Manager

http://developer.yahoo.com/yui/history/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.