简体   繁体   中英

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.

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.

You can do this using:

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

As described in this SO answer

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM