JQuery Trigger Event on Show/Hide of Element

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/

View Comments

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

  • 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?

  • 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.

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

  • Excellent!

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

    Here is an example:
    [code language="javascript"]
    (function ($) {
    $.each(['fadeIn', 'fadeOut'], function (i, ev) {
    var el = $.fn[ev];
    $.fn[ev] = function () {
    this.trigger(ev);
    return el.apply(this, arguments);
    };
    });
    })(jQuery);
    [/code]

    • //Specific element ... .
      $('#foo').on('hide', function(){
      $('#console').html( $('#console').html() + '#foo is hidden'+ '' )
      });

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

4 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

4 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

4 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

4 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

4 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

4 years ago