0

I am trying to make smooth scrolling in a single page application. In order to do this I am using window.location.hash statement in a click event handler like:

 $('a').on('click', function(event) {
   event.preventDefault();
   let hash = this.hash;
   if (hash !== '') { 
   window.location.hash = hash
   // _scrollTo();
   }
 })

I am binding window's hashchange event to the above _scrollTo() function so that when user tries to get the url with hash, application should scroll there:

$(window)
.on("hashchange", _scrollTo)
.trigger("hashchange")

Scrolling function is like this:

  const _scrollTo = function () {
    var destination = $('body').find(window.location.hash);
    _scrollToDestination(destination, configMap.duration);
  }

I need to use this function because of fixed header on top of page, I dont want the scrolling to a section would be under header and user does not see that

  const _scrollToDestination = function (destination, duration) {
    let headerHeight = $('header').outerHeight(true);
    $('html, body').animate({
      scrollTop: destination.offset().top - headerHeight
    }, duration);
  }

The problem is when I use the window.location.hash statement in click handler, event handler behaves as if default behaviour not prevented and I get weird results.

Codepen

Any help is appreciated. Thanks.

  • You are preventing the anchors mechanism but change the hash manually. That triggers another event in window actually. – Alex May 06 '21 at 13:57
  • Also, it might be that you cannot change the auto scroll behaviour. You can either use a simple hack: https://stackoverflow.com/questions/13328647/prevent-default-behavior-when-setting-location-hash or change the target markup that the browser doesnt find the elements (use data-id instead of id/ name for instance) – Alex May 06 '21 at 14:05

1 Answers1

0

Simply preventing the default behaviour of window.location... worked for me

How can I update window.location.hash without jumping the document?

Abdurakhmon
  • 2,813
  • 5
  • 20
  • 41