Search code examples
javascriptjqueryanchorsmooth-scrolling

Link to anchor on another page with smooth scrolling


I have searched high and low for this answer but can't seem to find it.

I have anchors on the homepage with links in the top menu that scroll to them.

This works great on the homepage but on the sub-pages it doesn't work.

Below is my code:

$(document).ready(function(){
  // Add smooth scrolling to all links
  $("a").on('click', function(event) {

    // Make sure this.hash has a value before overriding default behavior
    if (this.hash !== "") {
      // Prevent default anchor click behavior
      event.preventDefault();
      event.stopPropagation();
      // Store hash
      var hash = this.hash;

      // Using jQuery's animate() method to add smooth page scroll
      // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
      $('html, body').animate({
          scrollTop: $(hash).offset().top
        }, 2000, function(){

          // Add hash (#) to URL when done scrolling (default click behavior)
          window.location.hash = hash;
      });
    } // End if
  });
});

I have so far found that removing the event.preventDefault() line makes them work. But it stops the nice smooth scrolling effect.

What can be altered here so that I can have anchor links clicked on sub-pages that lead to the anchor section on the homepage with a smooth scroll ?


Solution

  • use return false; instead after scroll, and remove event.preventDefault & event.stopPropagation()

    try below code:

    $(document).ready(function() {
      // Add smooth scrolling to all links
      $("a").on('click', function(event) {
    
        // Make sure this.hash has a value before overriding default behavior
        if (this.hash !== "") {
    
          // Store hash
          var hash = this.hash;
    
          // Using jQuery's animate() method to add smooth page scroll
          // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
          $('html, body').animate({
            scrollTop: $(hash).offset().top
          }, 2000, function() {
    
            // Add hash (#) to URL when done scrolling (default click behavior)
            window.location.hash = hash;
          });
          return false;
        } // End if
      });
    });