Skip to content

Instantly share code, notes, and snippets.

@yairEO
Last active December 25, 2015 19:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yairEO/7030050 to your computer and use it in GitHub Desktop.
Save yairEO/7030050 to your computer and use it in GitHub Desktop.
scroll to position - jQuery plugin
////////////////////////////////////////
// Scroll To / jQuery plugin
//
// @author Yair Even Or
// @version 1.0.0 (April 3, 2013)
//
(function($){
"use strict";
var currentPos = 0,
pos = 0,
duration = 0,
topOffset = 0,
root = $('html, body'),
scrollTarget;
// jumpIn - in which container to scroll
$.fn.scrollToPos = function(jumpIn, quick, offset){
topOffset = offset != undefined ? offset : 25;
jumpIn = jumpIn || root;
if( quick ){
pos = $(this).offset().top;
jumpIn[0].scrollTop = pos + topOffset;
}
else{
scrollToPos.call(this, null, this, jumpIn);
}
}
function scrollToPos(e, jumpTo, jumpIn){
//if( root.is(':animated') )
// return false;
scrollTarget = jumpTo || $(this).data('scrollto') || $(this).attr('href');
// scrollTarget can be either an element selector or a number
if( $(scrollTarget).length )
pos = $(scrollTarget).offset().top;
else if( typeof pos != 'number' )
return this;
currentPos = $(document).scrollTop();
duration = Math.abs(currentPos - pos) * 2; // daley is relative to the jump distance
jumpIn.stop().animate({ scrollTop: (pos + topOffset)}, duration, 'easeOutQuint');
return this;
};
// initialize the plugin
//$(document).on('click.scrollTop', 'a[data-scrollTo]', scrollToPos);
$(document).on('click.scrollTo', 'a[data-scrollTo]', scrollToPos);
// custom easing functions
$.easing.jswing = $.easing.swing;
$.extend($.easing, {
easeInQuint: function (e, f, a, h, g) {
return h * (f /= g) * f * f * f * f + a;
},
easeOutQuint: function (e, f, a, h, g) {
return h * ((f = f / g - 1) * f * f * f * f + 1) + a;
},
easeInOutQuart: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
return -c/2 * ((t-=2)*t*t*t - 2) + b;
},
easeInOutCirc: function (x, t, b, c, d) {
if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
}
});
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment