Home >Web Front-end >JS Tutorial >How can I detect element visibility during scrolling with jQuery?
When navigating a web page with extensive content, it becomes essential to trigger specific actions when users reach particular elements. This article demonstrates how to use jQuery to trigger an event when a user scrolls to a designated HTML element.
Consider an HTML page with an h1 element positioned far down:
<code class="html"><h1 id="scroll-to">TRIGGER EVENT WHEN SCROLLED TO.</h1></code>
The objective is to display an alert when the user's browser view reaches the h1 element. While one may initially attempt to use the scroll() method on the h1 element:
<code class="js">$('#scroll-to').scroll(function() { alert('you have scrolled to the h1!'); });</code>
this approach will not yield the desired result. Instead, it is necessary to calculate the element's offset relative to the page and compare it to the scroll position.
<code class="js">$(window).scroll(function() { var hT = $('#scroll-to').offset().top, hH = $('#scroll-to').outerHeight(), wH = $(window).height(), wS = $(this).scrollTop(); if (wS > (hT + hH - wH)) { console.log('H1 on the view!'); } });</code>
The above code checks if the bottom of the h1 element has been reached within the visible portion of the page.
The above is the detailed content of How can I detect element visibility during scrolling with jQuery?. For more information, please follow other related articles on the PHP Chinese website!