How to write onshow event using javascript/jquery?

后端 未结 4 956
温柔的废话
温柔的废话 2021-02-02 16:41

I have an anchor tag on my page, i want an event attached to it, which will fire when the display of this element change.

How can i write this event? and catch whenever

4条回答
  •  不知归路
    2021-02-02 17:24

    This is my way of doing on onShow, as a jQuery plugin. It may or may not perform exactly what you are doing, however.

    (function($){
      $.fn.extend({ 
        onShow: function(callback, unbind){
          return this.each(function(){
            var _this = this;
            var bindopt = (unbind==undefined)?true:unbind; 
            if($.isFunction(callback)){
              if($(_this).is(':hidden')){
                var checkVis = function(){
                  if($(_this).is(':visible')){
                    callback.call(_this);
                    if(bindopt){
                      $('body').unbind('click keyup keydown', checkVis);
                    }
                  }                         
                }
                $('body').bind('click keyup keydown', checkVis);
              }
              else{
                callback.call(_this);
              }
            }
          });
        }
      });
    })(jQuery);
    

    You can call this inside the $(document).ready() function and use a callback to fire when the element is shown, as so.

    $(document).ready(function(){
      $('#myelement').onShow(function(){
        alert('this element is now shown');
      });
    });
    

    It works by binding a click, keyup, and keydown event to the body to check if the element is shown, because these events are most likely to cause an element to be shown and are very frequently performed by the user. This may not be extremely elegant but gets the job done. Also, once the element is shown, these events are unbinded from the body as to not keep firing and slowing down performance.

提交回复
热议问题