Search code examples
javascriptjqueryhyperlinkanchorsmooth-scrolling

JS Smooth Scrolling on Load interferes with Smooth Scrolling on Click


I'm new to JS, trying to make the following code work so that the homepage automatically scrolls on load and anchor links on other pages scroll smoothly on click...

<script>

    $(function(){
    $('html, body').animate({
    scrollTop: $('.destination').offset().top
    }, 2000);
    return false;

    $('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
        }, 2000);
        return false;
      }
    }
   });
   });

</script>

Any help would be much appreciated!

Thanks, Andreas


Solution

  • It is because you are closing the function by returning false earlier. Try:

     $(function(){
        $('html, body').animate({
        scrollTop: $('.destination').offset().top
        }, 2000);
    
        $('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
            }, 2000);
            return false;
          }
        }
       });
       });