Smooth horizontal scrolling inside a div [closed]
By editing solution for this question: Smooth vertical scrolling on mouse wheel in vanilla javascript? I managed to convert the scrolling from vertical to horizontal and I like the effect it does (smooth scrolling). But it works only on the body and I wonder if there is a way to do it only inside a specific div with editing further this code:
<body onload="init()">
<div id="sliderbar">
function init() {
new SmoothScroll(document, 120, 12)
}
function SmoothScroll(sliderbar, speed, smooth) {
if (sliderbar === document)
sliderbar = (document.scrollingElement ||
document.documentElement ||
document.body.parentNode ||
document.body) // cross browser support for document scrolling
var moving = false
var pos = sliderbar.scrollLeft
var frame = sliderbar === document.body &&
document.documentElement ?
document.documentElement :
sliderbar // safari is the new IE
sliderbar.addEventListener('mousewheel', scrolled, {
passive: false
})
sliderbar.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, sliderbar.scrollWidth - frame.clientWidth)) // 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 - sliderbar.scrollLeft) / smooth
sliderbar.scrollLeft += 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);
}
);
}()
}
Here's the fiddle: https://jsfiddle.net/Krasska/kz0c82pr/47/
Or do I need some other code to begin with since it uses onload event which can't be applied to a div?
from Recent Questions - Stack Overflow https://ift.tt/3FHuyPf
https://ift.tt/eA8V8J
Comments
Post a Comment