jQuery event to trigger action when a div is made visible

后端 未结 22 2207
你的背包
你的背包 2020-11-22 12:03

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\" even

22条回答
  •  囚心锁ツ
    2020-11-22 12:31

    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.

提交回复
热议问题