views:

32

answers:

4

Hi i want to trig a function when user click in page links for example abc.com/hello.html#variable1 i want to catch #varible1 and execute a function.

A: 

To attach logic to all hash-links, you can do the following:

$("a[href^='#']").click(function(e){
  // user clicked an inpage link
});
Jonathan Sampson
+1  A: 

If you want to grab the string after the hash:

$("a[href*='#']").click(function() {
    var hash = this.href.replace(/#(.*)$/, '$1');
    // do something
    return false
});
nickf
+1  A: 

Capture the hash and substring it out:

$("a[href*='#']").click(function(e){
  var hash = $(this).attr('href').substring($(this).attr('href').indexOf("#"));
  //hash = #var
  function(hash);
});
Nick Craver
A: 

If you want to trigger a function for links with hashes that are dynamically inserted, use this:

$(document).click(function (event) {
    var target = $(event.target);
    if (target.filter("a[href*='#']").size() > 0) {
        var hash = target.attr("hash");

        // Do something with hash.

        event.preventDefault();
    }
});
yungsters