jQuery: creating a custom event to check element's visibility

jQuery: creating a custom event to check element's visibility

How to fire an event when an element is shown or hidden with jQuery.

The sad truth about DOM Mutation Events is that they're poorly supported by web browsers. In order to create a custom event which fires every time an element has been hidden or not, we have to follow a different approach with jQuery.

We can set up a JavaScript timer which periodically tests the visibility of a given element:


$(function() {

	$( '#box' ).on( 'visibility', function() {
		var $element = $( this );
		var timer = setInterval( function() {
			if( $element.is( ':hidden' ) ) {
				$( '#status' ).text( 'Hidden' );
			} else {
				$( '#status' ).text( '' );
			}
		}, 300 );
	}).trigger( 'visibility' );
	
	$( '#test' ).on( 'click', function() {
		$( '#box' ).fadeOut( 1000 );
	
	});

});

300 milliseconds is a reasonable time interval. The final result is almost immediate.

[view-example url="http://codepen.io/gabrieleromanato/pen/Ijbcz"]