Home >Web Front-end >JS Tutorial >How Can I Detect When a User Scrolls to the Bottom (or Near the Bottom) of a Web Page Using jQuery?
Monitor Scrolling Depth for Precise Content Loading
In a pagination system where content loads upon reaching the bottom, determining when a user has scrolled to the extremity becomes crucial. jQuery provides an elegant solution to this challenge.
Method:
Execute the .scroll() event on the window object:
$(window).scroll(function() { // Calculate total scroll position and compare it to document height if($(window).scrollTop() + $(window).height() == $(document).height()) { alert("bottom!"); } });
This code sums the window's top scroll position (how far down it's scrolled) with the visible window's height, and compares this to the overall content height. When these values align, it signifies the user reaching the page bottom.
Near Bottom Detection:
For scenarios where you want to trigger an action before the actual bottom, modify the code as follows:
$(window).scroll(function() { // Check if user is within 100 pixels from the bottom if($(window).scrollTop() + $(window).height() > $(document).height() - 100) { alert("near bottom!"); } });
By adjusting the value after - 100 (e.g., to 50, 200), you can define the desired proximity threshold to the bottom.
The above is the detailed content of How Can I Detect When a User Scrolls to the Bottom (or Near the Bottom) of a Web Page Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!