JQuery Trigger Event on Show/Hide of Element

jquery-logoJQuery provides powerful API to manage triggering of events. It provides a way to trigger the event handlers bound to an element without any user interaction via the .trigger() method.

The .on() method (previously known as .live()) is a great way to add custom handlers to different browser events. When such events are triggered, these custom handlers are executed. This gives a great way to handle such events and perform certain activities.

The on() method can be used to add handlers to many build in events such as ‘click’, ‘change’ etc.

$('#foo').on('click', function() {
      console.log('the foo was clicked');
});

However sometimes we want to add custom handler to events that JQuery does not implicitly provides.

One such useful event is on show or hide of an element. Lets say we want to add a handler when a particular DIV is shown.

Although this is not implicitly present in JQuery, we can still achieve this by writing a custom code that triggers the show/hide event when a DIV visibility is changed.

Just add below JQuery code snippet in your javascript file and voila, you can now handler ‘show’/’hide’ events using .on() method similar to other implicit events.

(function ($) {
	  $.each(['show', 'hide'], function (i, ev) {
	    var el = $.fn[ev];
	    $.fn[ev] = function () {
	      this.trigger(ev);
	      return el.apply(this, arguments);
	    };
	  });
	})(jQuery);

Once the code is in place, you can simply use .on() method as below to add custom handler to show/hide event to any element.

$('#foo').on('show', function() {
      console.log('#foo is now visible');
});

$('#foo').on('hide', function() {
      console.log('#foo is hidden');
});

Online Demo

Here is a quick demo:

HTML Code





CSS Code

.container {
    height:60px;
    margin:10px;
}
#foo {
    background-color:#eeeeee;
    width:150px;
    height:50px;
    text-align:center;
    font-size:20px;
}

JQuery Code

//The magic code to add show/hide custom event triggers
(function ($) {
	  $.each(['show', 'hide'], function (i, ev) {
	    var el = $.fn[ev];
	    $.fn[ev] = function () {
	      this.trigger(ev);
	      return el.apply(this, arguments);
	    };
	  });
	})(jQuery);



//on Show button click; show the #foo div
$('#btnShow').click(function(){
   $('#foo').show();
});

//on Hide button click; hide the #foo div
$('#btnHide').click(function(){
   $('#foo').hide();
});

//Add custom handler on show event and print message
$('#foo').on('show', function(){
    $('#console').html( $('#console').html() + '#foo is now visible'+ '
' ) }); //Add custom handler on hide event and print message $('#foo').on('hide', function(){ $('#console').html( $('#console').html() + '#foo is hidden'+ '
' ) });

JSFiddle: http://jsfiddle.net/viralpatel/975wJ/