jQuery event to trigger action when a div is made visible

后端 未结 22 2233
你的背包
你的背包 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:23

    There is no native event you can hook into for this however you can trigger an event from your script after you have made the div visible using the .trigger function

    e.g

    //declare event to run when div is visible
    function isVisible(){
       //do something
    
    }
    
    //hookup the event
    $('#someDivId').bind('isVisible', isVisible);
    
    //show div and trigger custom event in callback when div is visible
    $('#someDivId').show('slow', function(){
        $(this).trigger('isVisible');
    });
    
    0 讨论(0)
  • 2020-11-22 12:24

    You can also try jQuery appear plugin as mentioned in parallel thread https://stackoverflow.com/a/3535028/741782

    0 讨论(0)
  • 2020-11-22 12:25

    I did a simple setinterval function to achieve this. If element with class div1 is visible, it sets div2 to be visible. I know not a good method, but a simple fix.

    setInterval(function(){
      if($('.div1').is(':visible')){
        $('.div2').show();
      }
      else {
        $('.div2').hide();
      }      
    }, 100);
    
    0 讨论(0)
  • 2020-11-22 12:25
    <div id="welcometo">Özhan</div>
    <input type="button" name="ooo" 
           onclick="JavaScript:
                        if(document.all.welcometo.style.display=='none') {
                            document.all.welcometo.style.display='';
                        } else {
                            document.all.welcometo.style.display='none';
                        }">
    

    This code auto control not required query visible or unvisible control

    0 讨论(0)
  • 2020-11-22 12:26

    I had this same problem and created a jQuery plugin to solve it for our site.

    https://github.com/shaunbowe/jquery.visibilityChanged

    Here is how you would use it based on your example:

    $('#contentDiv').visibilityChanged(function(element, visible) {
        alert("do something");
    });
    
    0 讨论(0)
  • 2020-11-22 12:27

    The following code (pulled from http://maximeparmentier.com/2012/11/06/bind-show-hide-events-with-jquery/) will enable you to use $('#someDiv').on('show', someFunc);.

    (function ($) {
      $.each(['show', 'hide'], function (i, ev) {
        var el = $.fn[ev];
        $.fn[ev] = function () {
          this.trigger(ev);
          return el.apply(this, arguments);
        };
      });
    })(jQuery);
    
    0 讨论(0)
提交回复
热议问题