Function On Window.scroll And Get The Vertical Offset
How to call a function when the window is scrolled and how to get the amount of pixels the window has been vertically scrolled. I want to play an animation when a desired value
Solution 1:
You can use window.onscroll
without the use of jQuery
. That was what you were missing on your code. It should be window.onscroll
and to get the vertical scroll pixels use window.scrollY
window.onscroll = function (e) {
console.log(window.scrollY);
};
html, body{
height: 2000px;
}
Solution 2:
You need to wrap the window
object in $()
to use the scrollTop()
function on it.
$(window).scroll(functionMyFunc(e){
var y = $(window).scrollTop();
console.log(y);
});
html, body{
height: 2000px;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
In Javascript, you can add an event listener for the scroll event on the window and use window.pageYOffset
(for better cross-browser compatability) to get the amount of pixels scrolled vertically.
window.addEventListener("scroll", functionMyFunc(e){
var y = (window.pageYOffset !== undefined)
? window.pageYOffset
: (document.documentElement || document.body.parentNode || document.body).scrollTop;//for cross-browser compatabilityconsole.log(y);
});
html, body{
height: 2000px;
}
Post a Comment for "Function On Window.scroll And Get The Vertical Offset"