bratsun
6/26/2014 - 8:35 PM

Check hash and scroll to target

Check hash and scroll to target

$(function() {
  $('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
        }, 1000);
        return false;
      }
    }
  });
});
// scroller function

var $stupid = $('<div></div>')
.height(1)
.hide()
.appendTo('body');

var mobileHack = function() {
  $stupid.show();
  setTimeout(function() {
	$stupid.hide();
  }, 1);
};

function scroller($target, $offset) {
  
  var this_offset = $(window).scrollTop();
  var that_offset = $($target).offset();
  var offset_diff = Math.abs(that_offset.top - this_offset);
 
  var base_speed  = 100; // Time in ms per 1,000 pixels
  var speed       = (offset_diff * base_speed) / 200;
  if (speed < 1000) {
    speed = 1000;
  }
  
  $.smoothScroll({
    speed: speed,
    autoCoefficent: 2, // coefficient for "auto" speed
    easing: 'easeInOutCubic',
    afterScroll: mobileHack,
    offset: $offset,
    scrollTarget: $target
  });    
}

// check hash

var hash = window.location.hash;
if (typeof hash != 'undefined') {
  scroller(hash, -30);
}