Skip to content

Instantly share code, notes, and snippets.

@rolandtoth
Created July 15, 2015 11:31
Show Gist options
  • Save rolandtoth/21316dfaec20b5294896 to your computer and use it in GitHub Desktop.
Save rolandtoth/21316dfaec20b5294896 to your computer and use it in GitHub Desktop.
gotoByScroll
/**
Smooth scroll to element
gotoByScroll({
target: $(targetID),
speed: 700,
vOffset: 0,
easing: "easeInOutQuad",
onStart: function (trg) {
// your function...
},
onEnd: function (trg) {
// your function...
}
});
*/
function gotoByScroll(s) {
if (!s || !s.target) {
return false;
}
var topOffset = (s.target && s.target.length) ? parseInt(s.target.offset().top) : 0,
speed = ((s.speed && !isNaN(s.speed)) || s.speed === 0) ? parseInt(s.speed) : 500,
easing = (s.easing && $.easing.hasOwnProperty(s.easing)) ? s.easing : "swing",
enableOnStartinPosition = s.enableOnStartinPosition || false,
enableOnEndinPosition = s.enableOnEndinPosition || false,
vOffset = (s.vOffset && !isNaN(s.vOffset)) ? parseInt(s.vOffset) : 0,
onStart = (s.onStart && typeof s.onStart === "function") ? s.onStart : null,
onEnd = (s.onEnd && typeof s.onEnd === "function") ? s.onEnd : null,
documentObj = (window.webkitURL) ? "body" : "html",
inPosition = false;
topOffset = Math.floor(topOffset);
// check if object is already in position
if (s.target && s.target.length) {
if (topOffset + vOffset === $(document).scrollTop()) {
speed = 0;
inPosition = true;
}
}
// start callback
if (onStart) {
if (!inPosition || (inPosition && enableOnStartinPosition)) {
// do not proceed if callback returns false
if (onStart(s.target, speed, topOffset, vOffset) === false) {
return false;
}
}
}
$(documentObj).stop(true).animate({scrollTop: topOffset + vOffset}, speed, easing, function () {
// end callback
if (onEnd) {
if (!inPosition || (inPosition && enableOnEndinPosition)) {
onEnd(s.target, speed, topOffset, vOffset);
}
}
return this;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment