jQuery scroll event occurs when the user scrolls in the specified element. jQuery scroll() Method attaches an html element to the event handler function and this event handler function executes when the user scrolls inside the attached html element.
jQuery scroll() Method Syntax
$(window).scroll(function(){ //this code executes when the scroll event occurs. });
Here we have attached the window object $(window) to the event handler function, however you can attach any scrollable element(for example “div”) to the event handler function using scroll() method.
jQuery scroll() Example
In the following example we have a “div” element and we have attached this “div” element to the event handler function using scroll() method. When the user scroll inside this “div” element, the scroll counter, following the “div” element is updated simultaneously. Here we are counting the number of times user scroll inside the “div” element.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <script> var count = 0; $(document).ready(function(){ $("div").scroll(function(){ $("span").text( count= count+1); }); }); </script> </head> <body> <h2>jQuery scroll event example on Beginnersbook.com</h2> <div style="border:1px solid grey;width:250px;height:80px;overflow:scroll;"> I am just writing this text to fill the div box, whenever you scroll inside this div box, the scroll count should be displayed below. <br> The count changes simultaneously as you scroll the div element</div> <p>Scroll counter: <span>0</span></p> </body> </html>
Output:
Before we scrolled inside the “div” element:
This screenshot is taken before we have scrolled inside the “div” element.
After we have scrolled inside the “div” element:
This screenshot is taken after we have scrolled inside the “div” element. As you can see the scroll counter is updated on the screen. This scroll count updates simultaneously as and when we scroll inside “div” element.
Leave a Reply