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

Wordpressor picture Wordpressor · Jan 3, 2012 · Viewed 11.1k times · Source

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();
});

Answer

bardiir picture bardiir · Jan 3, 2012

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();
  }
});