apamphilon

Smooth scroll to anchor after loading new page

This will work for a submenu in WordPress.

// to top right away
if ( window.location.hash ) scroll(0,0);
// void some browsers issue
setTimeout( function() { scroll(0,0); }, 1);

$(function() {

  if ($('body').hasClass('PAGE_TEMPLATE_HERE')) {
    // your current click function
    $('#primary-menu a[href*="#"]:not([href="#"])').on('click', function(e) {
      e.preventDefault();
      $('html, body').animate({
        scrollTop: $($(this).attr('href')).offset().top + 'px'
      }, 1000, 'swing');
    });
  } else {
    $('#primary-menu a[href*="#"]:not([href="#"])').on('click', function(e) {
      e.preventDefault();
      if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
        var target = '#' + this.hash.slice(1);
        target = '/' + document.domain + '/LINK_HERE' + target;
        window.location.href = target;
      }
    });
  }

  // *only* if we have anchor on the url
  if(window.location.hash) {
    // smooth scroll to the anchor id
    $('html, body').animate({
        scrollTop: $(window.location.hash).offset().top + 'px'
    }, 1000, 'swing');
  }
});

Credit


Comments: