Home > Web Front-end > JS Tutorial > How to Trigger Events for Visible Divs in jQuery?

How to Trigger Events for Visible Divs in jQuery?

Mary-Kate Olsen
Release: 2024-10-31 10:30:02
Original
668 people have browsed it

How to Trigger Events for Visible Divs in jQuery?

Using jQuery to Trigger Events for Visible divs

In jQuery, you can attach an "isvisible" event handler to monitor the visibility of a div element and trigger specific actions when it becomes visible.

The provided pseudocode can be implemented as follows:

<code class="js">$(function () {
  $('#contentDiv').on('isVisible', function () {
    alert("do something");
  });
});</code>
Copy after login

This code assigns an event handler to the #contentDiv div that executes the alert function when the div becomes visible.

jQuery Extension Approach:

Alternatively, you can extend the .show() method to trigger events before and after the div is shown:

Extension:

<code class="js">jQuery(function ($) {
  var _oldShow = $.fn.show;

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

      obj.trigger('beforeShow');
      _oldShow.apply(obj, [speed, newCallback]);
    });
  };
});</code>
Copy after login

Usage:

<code class="js">$('#test')
  .on('beforeShow', function () {
    alert('beforeShow');
  })
  .on('afterShow', function () {
    alert('afterShow');
  })
  .show(1000, function () {
    alert('in show callback');
  })
  .show();</code>
Copy after login

With this approach, you can trigger events before and after the div is shown while maintaining the behavior of the original .show() method.

The above is the detailed content of How to Trigger Events for Visible Divs in 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