Search code examples
javascriptjqueryhtmlhiddenvisible

jQuery how to constantly check if element is hidden/visible?


I have a couple of HTML5 videos on my website (within a slider), they automatically cycle every x seconds (or when user clicks "next slide").

I want to stop the videos that are actually invisible to user, any ideas how to achieve that?

I was tryng to do something like that, but I guess there's "each" missing and it works after click instead all the time (ok, in fact it doesn't work because "this" is used wrong here I guess, but you get the point, sorry, I'm not a JS-guy at all :():

document.on('click', ".videojs:hidden", function(){
   alert('video hidden!');    
   jQuery(this).player.pause();
});

Solution

  • You might want to look into this:

    http://www.west-wind.com/weblog/posts/2008/Sep/12/jQuery-CSS-Property-Monitoring-Plugin-updated

    You can then do something like this:

    jQuery(".videojs").watch("display,visibility", function() { 
      if(!jQuery(".videojs").is(':visible'))
      {
        alert('video hidden!');    
        jQuery(".videojs").player.pause();
      }
    });