Home > Web Front-end > JS Tutorial > body text

How can you trigger actions when a div becomes visible using jQuery?

Susan Sarandon
Release: 2024-11-01 03:04:02
Original
407 people have browsed it

How can you trigger actions when a div becomes visible using jQuery?

Triggering Actions Upon div Visibility using jQuery

In jQuery, attaching an event handler that executes specific code when a div becomes visible is possible. To accomplish this, consider utilizing the following pseudocode:

$(function() {
  $('#contentDiv').isvisible(function() {
    alert("do something");
  });
});
Copy after login

This pseudocode effectively ensures that the alert will only fire when the #contentDiv div becomes visible.

To implement this functionality, you can extend the original .show() method in jQuery:

<code class="javascript">$.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');

    // Execute the original show() function with the new callback
    _oldShow.apply(obj, [speed, newCallback]);
  });
};</code>
Copy after login

This extension allows you to trigger 'beforeShow' and 'afterShow' events before and after the div is made visible.

For example, the following usage demonstrates the functionality:

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

The above is the detailed content of How can you trigger actions when a div becomes visible using 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