1

A web-page has some links:

<a href="#example-hash-1" class="link">example-1</a>
<a href="#example-hash-2" class="link">example-2</a>
<a href="#example-hash-n" class="link">example-n</a>

Clicking any on them it runs an event of hashchange and we going to handle it:

$(window).on('hashchange', function(event){

    // Is it possible (inside this handler) to find out which of a.link was clicked?

});

Or, is there another way to do it?

abdulmanov.ilmir
  • 1,325
  • 4
  • 15
  • 24

4 Answers4

1

While I believe adding click listeners to the actual links would be best, you could also search for the element that would have changed the hash as such:

$(window).on('hashchange', function(event){
    $('a[href$='+window.location.hash+']').action();
});
Carl K
  • 974
  • 7
  • 18
0

I think you could use onclick as an attribute in the tag or you could use the .click() event through jQuery. I think that will accomplish the same as the window on hashchange.

noahdotgansallo
  • 763
  • 1
  • 6
  • 15
0

event.target will hold which element triggered the event.

I can't check at the moment, but I believe that this also binds.

Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74
0

try this:

$(window).on('hashchange', function(event){

    var hash = location.hash;
    var $this = $(hash);
    alert($this.html());
});
num8er
  • 18,604
  • 3
  • 43
  • 57