Search code examples
javascriptjquerysmooth-scrolling

Smooth Scrolling jumps weirdly


$(function() {$('a[href*=#]:not([href=#])').click(function() {
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) {
    $('html,body').animate({
      scrollTop: target.offset().top
    }, 1000);
    if (target.length <= 1000) {
      $('html,body').animate({
        scrollTop: target.offset().top - 60
      }, 1000);
    };
    return false;
  }
}});});

I’m working with a nav bar that becomes fixed with a screen max-width < 1000px.
The height of the navigation bar is 60px. So it goes backwards with animation 60px if max-with < 1000px.

All this works fine, but my problem is that the page jumps weirdly only when the viewport is bigger than 1000px.


Solution

  • I think the problem is that you're not preventing the default click event. This means that the browser jumps to the #id you want (as this is default browser behavior) and then the smooth scroll kicks in a triggers the animation from the beginning, resulting in a quick jump.

    to fix it just block the default event with preventDefault();

    Quick example:

    $('selector').click(function(e) {
        e.preventDefault();
        // your code
    });
    

    Fixed code:

    $(function() {
        $('a[href*=#]:not([href=#])').click(function(e) {e.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) {
                    $('html,body').animate({
                        scrollTop: target.offset().top
                    }, 1000);
                    if (matchMedia('only screen and (max-width: 1000px)').matches) {
                        $('html,body').animate({
                            scrollTop: target.offset().top - 60
                        }, 1000);
    
                        window.location.hash = '#' + target[0].id;
    
                        return false;
                    }
                  }
                }
              }
        });
    });