Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery event to trigger action when a div is made visible

I'm using jQuery in my site and I would like to trigger certain actions when a certain div is made visible.

Is it possible to attach some sort of "isvisible" event handler to arbitrary divs and have certain code run when they the div is made visible?

I would like something like the following pseudocode:

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

The alert("do something") code should not fire until the contentDiv is actually made visible.

Thanks.

like image 460
frankadelic Avatar asked Aug 03 '09 23:08

frankadelic


1 Answers

You could always add to the original .show() method so you don't have to trigger events every time you show something or if you need it to work with legacy code:

Jquery extension:

jQuery(function($) {    var _oldShow = $.fn.show;    $.fn.show = function(speed, oldCallback) {     return $(this).each(function() {       var obj         = $(this),           newCallback = function() {             if ($.isFunction(oldCallback)) {               oldCallback.apply(obj);             }             obj.trigger('afterShow');           };        // you can trigger a before show if you want       obj.trigger('beforeShow');        // now use the old function to show the element passing the new callback       _oldShow.apply(obj, [speed, newCallback]);     });   } }); 

Usage example:

jQuery(function($) {   $('#test')     .bind('beforeShow', function() {       alert('beforeShow');     })      .bind('afterShow', function() {       alert('afterShow');     })     .show(1000, function() {       alert('in show callback');     })     .show(); }); 

This effectively lets you do something beforeShow and afterShow while still executing the normal behavior of the original .show() method.

You could also create another method so you don't have to override the original .show() method.

like image 137
Tres Avatar answered Oct 14 '22 00:10

Tres