Smooth scrolling and return button from popState to Firefox - double click

I am trying to implement a small code with which I can get a smooth scroll when I click on the anchor (and the anchor name appears after the animation), and I would like to return to the top of the page if I click the browser back button and refresh the URL (without the name #anchor).

Here is the code:

$(function() {
  // Smooth scrolling when clicking on anchor
  $('a[href*=#]:not([href=#])').click(function(event) {
    event.preventDefault();
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        var hash = this.hash; 
        $('html,body').animate({ scrollTop: target.offset().top - 55}, 300, function() {
          location.hash = hash;
          href = window.location.href;
          history.pushState({page:href}, null, href);
        });
        return false;
      }
    }
  });
  // Get smooth scrolling to the top whith back button of browser
  $(window).bind('popstate', function(event) {
    var state = event.originalEvent.state;
    var target = window.location.href.split('#');
    var href = target[0];
    if (state) {
      $('html,body').animate({ scrollTop: 0 }, 300, function() {
        window.location.href = href;
     })
   }
  });

  // First page loading
  window.onload = function() {
    history.replaceState({ path: window.location.href }, '');
  }
});

All of the above features work well in Safari and Chrome. But this does not apply to Firefox: after performing a smooth scrolling, I need to double-click the "Back" button to redirect it to the top of the page.

I saw https://stackoverflow.com/a/1666547/ ... and tried to do with and without event.preventDefault, also putting only:

$('html').animate

or $('body').animate

but the behavior remains the same.

- , .

+4
1

location.hash = hash;

, , FF.

   $('html').animate({ scrollTop: target.offset().top - 55}, 300, function() {
      href = window.location.href;
      history.pushState({page:href}, null, href.split('#')[0]+hash);
    });

, , $('html,body').animate , . html.

popstate , , :

if (state) {
  $('html,body').animate({ scrollTop: 0 }, 300)
0

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


All Articles