Last active
August 29, 2015 14:07
-
-
Save zakirt/f3de1a11a8e9bf3e38b3 to your computer and use it in GitHub Desktop.
Scroll to numeric position, DOM element, jQuery object, or jQuery selector
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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