Home > Web Front-end > JS Tutorial > How to Detect When a DIV Becomes Visible in the Viewport with jQuery?

How to Detect When a DIV Becomes Visible in the Viewport with jQuery?

Linda Hamilton
Release: 2024-10-29 13:26:29
Original
803 people have browsed it

How to Detect When a DIV Becomes Visible in the Viewport with jQuery?

Responding to Visibility Changes of a DIV using jQuery

jQuery provides a robust framework for handling DOM events, including window visibility events. In this article, we'll explore how to trigger specific actions when a particular DIV element becomes visible within the viewport.

Creating a Custom "isvisible" Event Handler

While jQuery does not natively provide an "isvisible" event handler, we can implement a custom solution using event listeners. Here's how:

$(function() {

  // Register a "isVisible" listener for the #contentDiv
  $('#contentDiv').on('isVisible', function() {
    alert("Div is now visible");
  });

  // Check for visibility changes and trigger the event
  $(window).scroll(function() {
    var topOfDiv = $('#contentDiv').offset().top;
    var bottomOfDiv = topOfDiv + $('#contentDiv').height();
    var topOfWindow = $(window).scrollTop();
    var bottomOfWindow = topOfWindow + $(window).height();

    if (topOfDiv >= topOfWindow && bottomOfDiv <= bottomOfWindow) {
      $('#contentDiv').trigger('isVisible');
    }
  });
});
Copy after login

Extension of the .show() Method

Alternatively, you can extend the existing ".show()" method to trigger a custom "afterShow" event after the element becomes visible. Here's a code snippet for this approach:

jQuery(function($) {

  var _oldShow = $.fn.show;

  $.fn.show = function(speed, oldCallback) {
    return $(this).each(function() {
      var obj = $(this),
        newCallback = function() {
          if ($.isFunction(oldCallback)) {
            oldCallback.apply(obj);
          }
          obj.trigger('afterShow');
        };

      // Trigger beforeShow event
      obj.trigger('beforeShow');

      // Use old show function with custom callback
      _oldShow.apply(obj, [speed, newCallback]);
    });
  }
});
Copy after login

The above is the detailed content of How to Detect When a DIV Becomes Visible in the Viewport with jQuery?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template