Created
December 2, 2016 07:54
-
-
Save kamlekar/f5349c92ea557331cfbbdcffa8a91f9a to your computer and use it in GitHub Desktop.
Smooth scrolling effect (depends on jQuery)
This file contains 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
$.fn.smoothScroll = function(selector, payload) { | |
// payload params | |
// @ (int) payload.timerValue: Determines the max time to show the smooth animation | |
// @ (jQuery Element) payload.scrollingElement: Determines the element to which the scroll is present | |
payload = payload || {}; | |
function getScrollingElement($el) { | |
return payload.scrollingElement || $el.parent(); | |
} | |
// Delegate event | |
$(selector).on('click', function(e) { | |
e.preventDefault(); | |
var timerValue = payload.timerValue || 1000; | |
var $el = $(e.currentTarget); | |
var $scrollingElement = getScrollingElement($el); | |
var currentScrollTop = $scrollingElement.scrollTop(); | |
var targetOffsetTop = $($el.attr('href')).offset().top; | |
var boundOffsetTop = $scrollingElement.parent().offset().top; | |
var containerScrollHeight = $scrollingElement[0].scrollHeight; | |
var newScrollTop = currentScrollTop + targetOffsetTop - boundOffsetTop; | |
// Animate | |
$scrollingElement.animate({ | |
'scrollTop': newScrollTop | |
}, | |
// Making animation similar for distance elements | |
(newScrollTop / containerScrollHeight) * timerValue | |
); | |
}) | |
} | |
// Usage | |
$().smoothScroll('a', { | |
timerValue: 1000, | |
scrollingElement: $('.container') | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment