Skip to content

Instantly share code, notes, and snippets.

@dbushell
Created November 22, 2012 13:10
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dbushell/4131104 to your computer and use it in GitHub Desktop.
Save dbushell/4131104 to your computer and use it in GitHub Desktop.
Animate scrolling to an element or offset
/*!
* requires jQuery
* usage:
* Scroller.to({ offset: 100 });
* Scroller.to({ target: $('#main') });
*
* advanced usage (with additional easing function not provided here)
* Scroller.to({ target: $('#main'), delay: 500, multiplier: 1.5, easing: 'easeOutQuad' });
*/
var Scroller = (function()
{
var scroll = {
options: {
el: $('html:not(:animated),body:not(:animated)'),
multiplier: 1,
offset: undefined,
easing: 'swing',
delay: 0
},
_scrolling: false
};
scroll.to = function(options)
{
var height = {
top: $(window).scrollTop(),
doc: $(document).height(),
win: $(window).height()
};
if (height.doc <= height.win) {
return;
}
var config = $.extend({}, scroll.options);
config = $.extend(config, options || {});
config.offset = isNaN(config.offset) ? config.target.offset().top : config.offset;
var offset = config.offset,
distance = Math.abs(height.top - offset);
if (height.top < offset) {
var max = height.doc - height.win;
if (offset > max) {
distance -= offset - max;
}
}
if (distance) {
if (scroll._scrolling) {
scroll.stop();
}
scroll._scrolling = true;
scroll.timeout = window.setTimeout(function() {
config.el.animate({ scrollTop: Math.floor(offset) }, distance * config.multiplier, config.easing, function()
{
scroll._scrolling = false;
});
}, config.delay);
}
};
scroll.stop = function()
{
if (scroll.timeout) {
window.clearTimeout(scroll.timeout);
scroll.timeout = null;
}
scroll.options.el.stop();
scroll._scrolling = false;
};
scroll.isScrolling = function()
{
return scroll._scrolling;
};
return scroll;
})();
@mattboon
Copy link

Will this work, as a general trigger for jump links?

$('.scroll-links a').click(function(){
    Scroller.to({ target: this.hash });
    return false
});

@dbushell
Copy link
Author

Without testing I think you'll need:

$('.scroll-links a').click(function(){
    Scroller.to({ target: $('#' + this.hash) });
    return false;
});

not sure if this.hash includes the # or not. Either way wrap it in a jQuery object :)

@mattboon
Copy link

Pretty sure it does ;)

Not using it myself, just sending it on

@dbushell
Copy link
Author

Wait probably more like this:

<a class="jump" href="#test">
$('.jump').on('click', function(e)
{
    Scroller.to({ target: $( this.href ) });
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment