SUBSCRIBE VIA RSS


Subscribe to our feed

Symfony Experts

Symfony Experts
If you have an urgent question for a symfony-related issue, this is the place to ask.

Topics

TWITTER

Stack Overflow


The old fashioned way

RECENT TUNES

November 21, 2008 – 5:39pm Javascript get window hash/anchor, get link target

There are two functions I find myself using all the time. They are very useful for javascript events that read the link href attribute to determine an action’s target.

function getHash() {
  var hash = window.location.hash;
  return hash.substring(1); // remove #
}
 
function getLinkTarget(link) {
  return link.href.substring(link.href.indexOf('#')+1);
}
Posted in  Uncategorized   |     |  delicious  Digg

5 Responses to “Javascript get window hash/anchor, get link target”

  1. I’d use a regexp for the second, but those are very useful.

    By Jon Williams on Nov 21, 2008

  2. Nice work. Sometimes I use question marks after my hash to specify actions:

    http://a.com#favorites?recent

    So this code is a useful extension of your function (useful to me at least!):


    function getHash(excludeQuestionMark) {
    if (typeof excludeQuestionMark == 'undefined') var excludeQuestionMark = true;
    var hash = window.location.hash;
    var stop = hash.indexOf('?');
    // if there was no question mark in the hash, or if excludeQuestionMark is set to false
    if (stop == -1 || !excludeQuestionMark)
    var returner = hash.substring(1); // remove #
    else
    var returner = hash.substring(1,stop); // remove # and exlude everything after '?'
    return returner;
    }

    By Mani Tadayon on Jan 5, 2009

  3. hmm nice code however i was just looking for how to get the hash value so what does the second one do??

    By Achshar on Aug 28, 2010

  4. You can easily get the hash from a link with the `hash` property.

    http://jsfiddle.net/bngtm/

    By Alex on Apr 6, 2011

  5. WHAT?!?!? Nice. That is awesome.

    By Scott Meves on Apr 6, 2011

Post a Comment

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word