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!