Trigger Action on Div Visibility with jQuery Event

When it comes to triggering actions based on the visibility of a <div> element, jQuery's .is(':visible') method comes in handy. This method returns a Boolean value indicating whether the selected element is currently visible or not.

To trigger an action when a <div> element becomes visible, you can use the .on() method to bind a custom event to the <div> element. Then, you can use the .is() method to check whether the element is visible or not within the custom event handler function.

<div id="myDiv">
   <p>This is my div.</p>
</div>

<script>
   $('#myDiv').on('customEvent', function() {
      if ($(this).is(':visible')) {
         // Do something when element is visible
      } else {
         // Do something when element is not visible
      }
   });

   $(window).on('scroll resize', function() {
      $('#myDiv').trigger('customEvent');
   });
</script>

In the example above, the custom event is bound to the <div> element with the .on() method. The event handler function checks whether the element is visible or not using the .is(':visible') method.

Finally, the custom event is triggered when the user scrolls or resizes the window using the .trigger() method.

By using this technique, you can easily trigger actions when a <div> element becomes visible or invisible on the page.

Click to rate this post!
[Total: 0 Average: 0]

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information