Skip to content

Instantly share code, notes, and snippets.

@zakirt
Last active August 29, 2015 14:07
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 zakirt/f3de1a11a8e9bf3e38b3 to your computer and use it in GitHub Desktop.
Save zakirt/f3de1a11a8e9bf3e38b3 to your computer and use it in GitHub Desktop.
Scroll to numeric position, DOM element, jQuery object, or jQuery selector
/**
* @author Zakir Tariverdiev
* @description jQuery scroll utility method alllowing animated scrolling
* to the specified entity.
* Chckout example http://jsfiddle.net/zakirt/hsb2v9ju/
* @param {number|string|Element|jQuery} - numeric position,
* jQuery selector string, DOM element, or jQuery object to scroll to.
* @returns promise object
*/
(function($) {
'use strict';
// Avoid possible conflicts with identically named jQuery method
if (typeof $.scrollTo === 'undefined') {
$.scrollTo = function(where, animDuration) {
var scrollPos = null;
if (typeof where !== 'undefined') {
// Numeric offset?
if (typeof where === 'number') {
scrollPos = where;
}
// String selector, or numeric value as string?
else if (typeof where === 'string') {
if (!isNaN(parseInt(where, 10))) {
scrollPos = parseInt(where, 10);
}
else if ($(where).length !== 0) {
scrollPos = $(where).offset().top;
}
}
// DOM element?
else if (typeof where.nodeType !== 'undefined' && where.nodeType === Node.ELEMENT_NODE) {
scrollPos = $(where).offset().top;
}
// jQuery instance
else if (where instanceof jQuery) {
scrollPos = where.offset().top;
}
}
// All went smoothly and we have a valid offset value
if (scrollPos !== null) {
var duration = animDuration || 600;
return $('body,html').animate({
scrollTop: scrollPos
}, duration).promise();
}
};
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment