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

When I have the following:

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

... and load it in the browser, I can add #testto the URL and the browser will scroll so that it is <a>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 would just do nothing.

Is there any way to do this without deleting the item <a>?


Update: I need the browser to send events anyway onhashchange(), but without scrolling to the item <a>. The reason is because I want to override the scroll while keeping the event notification.

+3
source share
5 answers

A quick dirty hack, but this is what you can rely on:

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 in different browsers and maintain the integrity of the onhashchange page and onscroll handlers. One of the problems I noticed is that if you click on the same hashtag twice, it will scroll anyway.


UPD. I just found 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)
  }
})
+2
source

Well, you can try to be cruel:

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

It should start after the DOM is ready, but before it is processed, so you must put it in the right place. It will not work for id attributes - only with <a name = ...>

Does he do what you want?

+1
source

:

$( 'a[href="#"]' ).click( function(e) {
  e.preventDefault();
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hide result
+1
source

The hacking technique is simply to automatically scroll to the top of the page if there is a hash in the URL:

if (window.location.hash) {
    window.scrollTo(0, 0);
}
0
source

maybe you need to use a little jquery and string manipulation

removeHashPartFromString = function() {
 ...
}

$('a').each(function() {
    this.attr('href') = removeHashPartFromString(this.attr('href'));
}); 

Or find hash elements and remove the name hash attributes from these elements.

-1
source

Source: https://habr.com/ru/post/1793277/


All Articles