Created
October 22, 2018 17:10
-
-
Save SamJakob/c9175a4c2440e1b14b0b8cf7d99d2d24 to your computer and use it in GitHub Desktop.
A vue-js supported smooth-scroll module based on a Stack Overflow answer by Manuel Otto.
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
const SmoothScroll = (target, speed, smooth) => { | |
if (target === document) | |
target = (document.documentElement || document.body.parentNode || document.body) // cross browser support for document scrolling | |
let moving = false; | |
let pos = target.scrollTop; | |
target.addEventListener('mousewheel', scrolled, false) | |
/* target.addEventListener('DOMMouseScroll', scrolled, false) */ | |
function scrolled(e) { | |
e.preventDefault(); // disable default scrolling | |
let delta = e.delta || e.wheelDelta; | |
if (delta === undefined) { | |
//we are on firefox | |
delta = -e.detail; | |
} | |
delta = Math.max(-1, Math.min(1, delta)) // cap the delta to [-1,1] for cross browser consistency | |
pos += -delta * speed | |
pos = Math.max(0, Math.min(pos, (target.scrollHeight - target.clientHeight) + (smooth * 2))) // limit scrolling | |
if (!moving) update() | |
} | |
function update() { | |
moving = true | |
let delta = (pos - target.scrollTop) / smooth; | |
delta -= 1; | |
if(pos - target.scrollTop === smooth * 2) | |
delta = 0; | |
target.scrollTop += delta | |
if (Math.abs(delta) > 0.5) | |
requestFrame(update) | |
else | |
moving = false | |
} | |
var requestFrame = function() { // requestAnimationFrame cross browser | |
return ( | |
window.requestAnimationFrame || | |
window.webkitRequestAnimationFrame || | |
window.mozRequestAnimationFrame || | |
window.oRequestAnimationFrame || | |
window.msRequestAnimationFrame || | |
function(func) { | |
window.setTimeout(func, 1000 / 50); | |
} | |
); | |
}() | |
} | |
export default SmoothScroll; |
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
<template> | |
... | |
</template> | |
<script> | |
import SmoothScroll from 'assets/js/smoothscroll'; | |
export default { | |
mounted () { | |
if(!window.smoothScroll){ | |
window.smoothScroll = SmoothScroll(document, 120, 12); | |
} | |
} | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@SamJakob hey sam, I figured a workaround for this, I'm just disabling window scroll for specific points and enabling it after a time out.
Regardless, this solution still helped me solve a bug that I had because of the scroll disabling so, thank you so much for taking the time to answer my doubt! :)