Home >Web Front-end >JS Tutorial >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"); }); });
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>
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>
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!