Reputation: 99
I have been messing around with a pure javascript solution to smooth scroll when you use the mousewheel, and I stumbled across this code which I tweaked to my needs. Everything works fine except the scrollbar. If you press and hold the scrollbar and move it down for example, when you release it and use the mousewheel again down let's say, it reverts back to the previous position of the mousewheel and in the opposite direction. My code:
init()
function init(){
new SmoothScroll(document,120,12)
}
//Smooth Scroll
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('DOMMouseScroll', scrolled, { passive: false })
target.addEventListener('mousewheel', 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) >= 1) 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 / 60);
}
);
}()
}
I made a fiddle to exemplify the issue https://jsfiddle.net/kgc85trn/
Any help would be greatly appreciated
Upvotes: 0
Views: 357
Reputation: 17
event mousescroll is no longer supported. or check the docs https://developer.mozilla.org/en-US/docs/Web/API/Element/mousewheel_event
Upvotes: 1