728x90


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.

shareimprove this question
up vote167down voteaccepted

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.

shareimprove this answer
5 
EDIT: There is only one downside with this method: You will have to repeat the same "extension" for all methods that reveal the element: show(), slideDown() etc. Something more universal is required to solve this problem for once and all, since its impossible to have "ready" event for delegate() or live(). – Shahriyar Imanov Feb 24 '11 at 17:59
   
Good, the only problem is that fadeTo function does not work properly after implementing this function – Omid Nov 11 '11 at 10:56
8 
Your code does not appear to work with the latest jQuery (1.7.1 at the date of this comment). I have reworked this solution slightly to work with the latest jQuery: stackoverflow.com/a/9422207/135968 – mkmurray Feb 23 '12 at 22:15
2 
Thanks mkmurray. It at least worked for a few years! – Tres Aug 15 '13 at 1:37
   
Can't get that code to work with div visibility triggered by an ajax response. – JackTheKnife Oct 7 '16 at 14:39


+ Recent posts