2

I have an internal link on my html page. Two things happen on clicking an internal link.

  1. Page is scrolled (jumped) so that the target of the link is at the top of the page.
  2. url reflects the internal link clicked by showing /abc/#...

I noticed that the order of these two steps is also the same. i.e. hashchange is fired after the scrolling has happened. I want to prevent the scrolling but allow hashchange to occur. If I write an onclickevent to return false (i.e. block it) then even the hashchange event is not fired. Any suggestions how else it could be done?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Parit
  • 152
  • 6
  • Have you tried `location.href = '/abc/#'; return false;`? –  Mar 05 '14 at 09:48
  • I guess you're still trying... –  Mar 05 '14 at 10:07
  • solved it by removing the element with the id that it refers to. Couldn't find the element couldn't scroll to it. Actually this link was used to open a panel and we wanted to make the resulting url as bookmarkable. i.e. if we had www.domain.org and a link Show Panel with id xyz, then this results in a url like www.domain.org#xyz which can be bookmarked. I simple removed the id xyz from the panel and hence panel is never scrolled to the top. Thankx for the answer though. – Parit Mar 25 '14 at 23:03

1 Answers1

0

You can use window.history.pushState() or window.history.replaceState(). Those methods do not scroll. Sadly, Internet Explorer supports history only since version 10.

Example:

document.body.addEventListener('click', function(oEvent)
{
    if (oEvent.target.nodeName == 'A'
    &&  oEvent.target.hasAttribute('href')
    &&  oEvent.target.getAttribute('href').charAt(0) == '#')
    {
        oEvent.preventDefault();
        history.pushState(null, '', oEvent.target.getAttribute('href'));
    }
}, false);

PS. My page should keep working with scripts disabled, so I keep element's ID, at least until some link was clicked.

CoolCmd
  • 939
  • 8
  • 13