mTuran
mTuran

Reputation: 1834

Catching in page links with jQuery

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.

Upvotes: 1

Views: 367

Answers (4)

nickf
nickf

Reputation: 546353

If you want to grab the string after the hash:

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

Upvotes: 2

yungsters
yungsters

Reputation: 44

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();
    }
});

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630589

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);
});

Upvotes: 1

Sampson
Sampson

Reputation: 268434

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

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

Upvotes: 0

Related Questions