Home >Web Front-end >JS Tutorial >How to Trigger an Event When Scrolling to a Specific Element in jQuery?

How to Trigger an Event When Scrolling to a Specific Element in jQuery?

Barbara Streisand
Barbara StreisandOriginal
2024-11-02 13:41:02952browse

How to Trigger an Event When Scrolling to a Specific Element in jQuery?

Trigger an Event when Reaching a Specific Element with jQuery

Problem

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.

Solution

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>

Enhancements

  • Demo Fiddle: A live example without the alert, instead fading in the h1 element.
  • Updated Code: Now checks if the element is within the viewport, regardless of scrolling direction.
  • Updated Demo Fiddle: Shows the functionality of the updated 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn