Link to new page and scroll to anchor

Hmm, this one was a littel trickier than I thought.

I quite often use jQuery Easing plugin to scroll nicely to sections using anchor links, but every so often you need to scroll to another page and to a specific section. This is all well and good when you want to scroll a one-page site or a link to a section on the same page.  But if you’re using a fixed header, it’s tricky to scroll to another page and scroll to the required section with a nice animation – which becomes tricky when you have a fixed header.

This requires jQuery Easing 1.3.1 to be installed first, but after you can do the following:

// start at the top
if ( window.location.hash ) scroll(0,0);
// avoid some browsers issues...
setTimeout( function() { scroll(0,0); }, 1);
$(function() {
  // if we are on same page, simply scroll down...
  $('.page-scroll').bind('click', function(event) {
    var $anchor = $(this);
    $('html, body').stop().animate({
      scrollTop: $($anchor.attr('href')).offset().top -65 // 65px fixed header
    }, 600, 'easeInOutExpo');
    event.preventDefault();
  });
  // if we have anchor on the URL from another page...
  if(window.location.hash) { // if anchor link to page
      // smooth scroll to the anchor id
      $('html, body').stop().animate({
         scrollTop: $(window.location.hash).offset().top -65 // 65px fixed header
      }, 600, 'easeInOutExpo');
  }
});

Useful post? Share it

Leave a Reply

Your email address will not be published.