1

window.scroll=function MyFunc(){
 var y = window.scrollTop();
 alert(y);
}
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 has been reached. Help.
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
nirbhay
  • 33
  • 1
  • 5
  • 2 things you'd like to take into consideration: #1) Is to use requestAnimationFrame (as the window.scroll makes the browser janky while scrolling). #2) Check out IntersectionObserver and a possible polyfill if you want to fire an animation based on an element's display on the viewport. – Jose A Aug 20 '18 at 14:36

2 Answers2

4

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;
}
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
2

You need to wrap the window object in $() to use the scrollTop() function on it.

$(window).scroll(function MyFunc(e){
 var y = $(window).scrollTop();
 console.log(y);
});
html, body{
  height: 2000px;
}
<script src="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", function MyFunc(e){
  var y = (window.pageYOffset !== undefined)
  ? window.pageYOffset
  : (document.documentElement || document.body.parentNode || document.body).scrollTop;//for cross-browser compatability
  console.log(y);
});
html, body{
  height: 2000px;
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80