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

How to Trigger Events for Visible Divs in jQuery?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-31 10:30:02556browse

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>

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>

Usage:

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

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!

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