zeshan-a
12/13/2016 - 4:22 AM

Smooth Anchor Links. This works with the anchor links in the URL too. It also changes the URL hash.

Smooth Anchor Links. This works with the anchor links in the URL too. It also changes the URL hash.

/**
 * Smooth Anchor Links
 *
 * This works with the anchor links in the URL too. It also changes the 
 * URL hash 
 *
 * Replace .offset_element_selector with the offset element, e.g., .navbar
 */
jQuery(document).ready(function($) {

  var hash         = window.location.hash,
      $offsetEl   = $('.offset_element_selector'),
      $links      = $('a[href^="#"]'),
      $wpadminbar = $('#wpadminbar');

  // Check if URL has hash and smooth scroll to that. 
  if ( hash ) {
    var $hashEl = $(hash);
    if ( $hashEl.length ) {
      scrollToAnchor( $hashEl );
      $(window).load(function() {
        scrollToAnchor( $hashEl );
      });
    }
  }

  $links.on('click', function(e) {
    var $this  = $(this),
        thisHref    = $this.attr('href');

    if ( thisHref !== '#' ) {
      if ( $(thisHref).length ) {
        e.preventDefault();
        scrollToAnchor( $(thisHref) );
      }
    }
  });

  function scrollToAnchor( $el ) {
    offset = $offsetEl.outerHeight() + $wpadminbar.outerHeight();
    $('html, body').animate({
      scrollTop: $el.offset().top - offset
    }, 500);
  }
});