Home >Web Front-end >JS Tutorial >How to Trigger an Event When Scrolling to a Specific Element in jQuery?
A user wants to display an alert message when scrolling down a webpage and reaching a specific h1 element. They attempted using the scroll() event but it didn't work.
To determine when the h1 element enters the browser's view, we need to calculate its offset from the top and compare it with the current scroll value. Here's the revised code:
<code class="javascript">$(window).scroll(function() { var hT = $('#scroll-to').offset().top, hH = $('#scroll-to').outerHeight(), wH = $(window).height(), wS = $(this).scrollTop(); if (wS > (hT+hH-wH) && wS < hT && wS+wH > hT+hH){ console.log('H1 on the view!'); // or trigger any desired event } });</code>
The above is the detailed content of How to Trigger an Event When Scrolling to a Specific Element in jQuery?. For more information, please follow other related articles on the PHP Chinese website!