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

<button id="btnShow">Show</button>
<button id="btnHide">Hide</button>
<div class="container">
<div id="foo">
    I am #foo
</div>
</div>
<div id="console">
</div>

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'+ '<br>'  )
});

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

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

Get our Articles via Email. Enter your email address.

You may also like...

15 Comments

  1. Alcides Melo says:

    This should works with Jquery tabs? For some reason, with me does not work properly.

  2. Pooya says:

    Thanks, Works fine.

  3. Mikhail says:

    Thanks, this works like a clock!;)

  4. Jeff says:

    Works great, except if you’re using Bootstrap modals. Do you know if there’s a way to limit it to trigger only on certain elements, and ignore others?

  5. iSenne says:

    Great code snippet, works perfectly :)

  6. mehul says:

    yes if anyone needs help just send me ur question to my mail id

  7. vikash says:

    Hi Viral,

    this is working for first time and then for next event its not working.
    How can I change this to check display:none or display:block instead of show / hide.

  8. Thingalore says:

    Please provide the complete Jquery set of code for left hand side hide and show menu

  9. DNA says:

    This code works, but just to warn anyone wanting to use it, it’s EXTREMELY slow, especially on older machines!

  10. SoursopTree says:

    Excellent!

    You can also use it for fadeIn fadeOut or other things!

    Here is an example:

    (function ($) {
          $.each(['fadeIn', 'fadeOut'], function (i, ev) {
            var el = $.fn[ev];
            $.fn[ev] = function () {
              this.trigger(ev);
              return el.apply(this, arguments);
            };
          });
    })(jQuery);
    
    • Joe Johnston says:

      //Specific element … .
      $(‘#foo’).on(‘hide’, function(){
      $(‘#console’).html( $(‘#console’).html() + ‘#foo is hidden’+ ” )
      });

  11. Sathish says:

    Hi,
    This code works on all element on show and hide. I what to handle the event on specific elelment only. Can you tell me how to do that.

    Regards,
    N.Sathish

  12. Franco says:

    Excelent it works!

  13. Joe Johnston says:

    This is the good stuff. Thanks for posting!

  14. Sarav says:

    Great stuff – thanks a looooott!!!

Leave a Reply

Your email address will not be published. Required fields are marked *