Jquery Scrolltop() Returns Value Of Previous Scroll Position
I am using jquery function element.scrollTop() to get the current scroll position of the page using following line: var currentScrollPosition= $('html').scrollTop() || $('body').s
Solution 1:
The issue is because the mousewheel event fires when the mousewheel movement starts. You are reading the scrollTop
at the point before the update has happened. You need to use a timer to get the scrollTop
after the mouse wheel scroll has finished. Try this:
document.addEventListener("mousewheel", MouseWheelHandler);
var cumulativeDelta = 0,
functionCallCount = 0,
currentScrollPosition = 0;
functionMouseWheelHandler(e) {
e = window.event || e; // 'event' with old IE supportvar delta = e.wheelDelta || -e.detail; // get delta value
cumulativeDelta += delta;
functionCallCount += 1;
setTimeout(function() {
currentScrollPosition = $(window).scrollTop();
document.getElementById("info4").innerHTML = "currentScrollPosition:" + currentScrollPosition;
}, 200); // update currentScrollPos 200ms after event firesdocument.getElementById("info1").innerHTML = "delta:" + delta;
document.getElementById("info2").innerHTML = "cumulativeDelta:" + cumulativeDelta;
document.getElementById("info3").innerHTML = "functionCallCount:" + functionCallCount;
}
body {
height: 2000px;
border: solid red 3px;
}
.normalPart {
border: solid green 2px;
height: 900px;
}
.stationary {
position: fixed;
top: 0px;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script><divclass="stationary"><divid="info1"></div><divid="info2"></div><divid="info3"></div><divid="info4"></div></div>
Alternatively you could read the currentScrollTop
position directly on the scroll event of the window as that will always be in sync with its current position.
Solution 2:
I would listen for the scroll
event instead of wheel
. Scroll activates after the scrollTop
value has been updated.
target.onscroll = functionRef
Great example here
Post a Comment for "Jquery Scrolltop() Returns Value Of Previous Scroll Position"