Created
March 14, 2023 12:16
-
-
Save yaroslav-borodii/f9b9409bb3ae1e23c347660fd5071bb9 to your computer and use it in GitHub Desktop.
Smooth vertical scrolling on mouse wheel in vanilla javascript
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
/** | |
* Smooth Vertical Scrolling on mouse wheel in vanilla JavaScript | |
*/ | |
function init(){ | |
new SmoothScroll(document, 30, 18) | |
} | |
function SmoothScroll(target, speed, smooth) { | |
if (target === document) | |
target = (document.scrollingElement | |
|| document.documentElement | |
|| document.body.parentNode | |
|| document.body) // cross browser support for document scrolling | |
var moving = false | |
var pos = target.scrollTop | |
var frame = target === document.body | |
&& document.documentElement | |
? document.documentElement | |
: target // safari is the new IE | |
target.addEventListener('mousewheel', scrolled, { passive: false }) | |
target.addEventListener('DOMMouseScroll', scrolled, { passive: false }) | |
function scrolled(e) { | |
e.preventDefault(); // disable default scrolling | |
var delta = normalizeWheelDelta(e) | |
pos += -delta * speed | |
pos = Math.max(0, Math.min(pos, target.scrollHeight - frame.clientHeight)) // limit scrolling | |
if (!moving) update() | |
} | |
function normalizeWheelDelta(e){ | |
if(e.detail){ | |
if(e.wheelDelta) | |
return e.wheelDelta/e.detail/40 * (e.detail>0 ? 1 : -1) // Opera | |
else | |
return -e.detail/3 // Firefox | |
}else | |
return e.wheelDelta/120 // IE,Safari,Chrome | |
} | |
function update() { | |
moving = true | |
var delta = (pos - target.scrollTop) / smooth | |
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); | |
} | |
); | |
}() | |
} | |
init() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment