Jan
Jan

Reputation: 6848

Intercept named anchor in javascript

Imagine, someone types http://example.com/somepage#someanchor in his browser address bar. How could I intercept this call to the anchor, display the page normally (don't scroll to the anchor) and do something instead in javascript, like alerting 'someanchor'. All in js, no server side redirects (to something like somepage?anchor=someanchor).

Any ideas? Is this possible at all? It would be easy to intercept clicks to anchors, I control, but this is not the case here.

Upvotes: 4

Views: 2015

Answers (3)

Michele Ricciardi
Michele Ricciardi

Reputation: 2117

You can do this using:

$(window).on('hashchange', function() {
  //prevent default, then your code
});

As described in this SO answer

Upvotes: 2

Pav
Pav

Reputation: 2328

Check out Ben Alman's hashchange plug-in http://benalman.com/projects/jquery-hashchange-plugin/ which solves cross-browser issues

Upvotes: 0

David Titarenco
David Titarenco

Reputation: 33406

Intercepting it is easy (call this from your onload handler):

function getHash() {
  var hash = window.location.hash;
  return hash.substring(1); // remove #
}

To prevent the window from scrolling down to said anchor, you may have to scroll back up on the onload event.

Upvotes: 4

Related Questions