JQuery Trigger Event on Show/Hide of Element

jquery-logo

JQuery 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'); });
Code language: JavaScript (javascript)

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);
Code language: JavaScript (javascript)

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'); });
Code language: JavaScript (javascript)

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>
Code language: HTML, XML (xml)

CSS Code

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

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>' ) });
Code language: JavaScript (javascript)

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

Get our Articles via Email. Enter your email address.

You may also like...

18 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. 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!!!

  15. John says:

    This breaks if you have an element inside the container that you’ve attached the event to and then hide/show that element. It creates an infinite recursive loop.

    Here’s a fiddle with an example:
    http://jsfiddle.net/itzfender/swaqfpk0/

  16. Lima (from Brazil) says:

    Thank you very much, it still working :)

  17. Jon T says:

    Awesome tutorial – thank you very much… this helped me out today.

Leave a Reply

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