Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to override the browser's default behavior for clicking on hashes?

When I have the following:

<a name='test'></a>

...and load it in a browser, I can append #test to the URL and the browser will scroll so that the <a> is at the top of the page.

However, I would like to change this behavior (using JavaScript if possible) so that using the hash does not scroll the page - I'd like it to simply do nothing.

Is there a way to do that without removing the <a> element?


Update: I need the browser to still send onhashchange() events but without scrolling to the <a> element. The reason being that I want to override the scrolling while retaining the event notification.

like image 604
Nathan Osman Avatar asked Nov 15 '25 15:11

Nathan Osman


2 Answers

A quick dirty hack, but it's something you can build upon:

var curScroll = prevScroll = $(window).scrollTop()

$(window).bind('scroll', function() {
  prevScroll = curScroll
  curScroll = $(this).scrollTop()
}).bind('hashchange', function() {
  $(this).scrollTop(prevScroll)
})

I used jQuery here to make it work across browsers and keep the page's onhashchange and onscroll handlers intact. One problem I spotted is that if you click the same hashtag twice it scrolls anyway.


UPD. I just figured out a better solution:

$('a').live('click', function() {
  if (this.href.split('#')[0] == location.href.split('#')[0]) {
    var scrollTop = $(window).scrollTop()
    setTimeout(function() {
      $(window).scrollTop(scrollTop)
    }, 0)
  }
})
like image 155
Alexey Lebedev Avatar answered Nov 18 '25 03:11

Alexey Lebedev


Well, you can try to be brutal:

var i, elems = document.getElementsByTagName('a');
for (i = 0; i < elems.length; i++) {
    elems[i].removeAttribute('name');
}

It has to be run after the DOM is ready but before it gets rendered so you have to put it in the right place. It won't work for 'id' attributes - only with <a name=...>

Does it do what you want?

like image 22
rsp Avatar answered Nov 18 '25 03:11

rsp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!