Skip to content

Instantly share code, notes, and snippets.

@kairyou
Last active June 17, 2020 09:57
Show Gist options
  • Save kairyou/4aaca43d1528d042fa4c to your computer and use it in GitHub Desktop.
Save kairyou/4aaca43d1528d042fa4c to your computer and use it in GitHub Desktop.
jquery on show hide event
(function($) {
$.each(['show', 'hide'], function(i, ev) {
var el = $.fn[ev];
$.fn[ev] = function() {
this.trigger(ev);
return el.apply(this, arguments);
};
});
})(jQuery);
//
$('#foo').on('show', function() {
console.log('#foo is now visible');
});
$('#foo').on('hide', function() {
console.log('#foo is hidden');
});
$('#foo').show().hide();
// http://viralpatel.net/blogs/jquery-trigger-custom-event-show-hide-element/
@mafar
Copy link

mafar commented Mar 4, 2016

this does not support easing and other arguments

@wpsoul
Copy link

wpsoul commented Apr 29, 2016

This code can break tabs, accorditions scripts of most of plugins

@kingofnull
Copy link

kingofnull commented Dec 8, 2016

This support easing and trigger event after animation done!

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

@DantaliaN00
Copy link

DantaliaN00 commented Mar 3, 2017

if I do something like

<div id="test">
  <div id="inner"></div>
</div>

and in code

$("#test").on("show", function(e) {
  console.log(e.target); //here I get #inner.. but I expect only #test
})

$("#inner").show();

how to fix it?

@DantaliaN00
Copy link

Oh.. found

change trigger to triggerHandler for stop bubbling

@Sagleft
Copy link

Sagleft commented Aug 5, 2019

DantaliaN00, thanks, helped

@nealshail
Copy link

nealshail commented Jun 17, 2020

thanks, I had the same issue.. fixed it for me too.. so it will be

(function ($) {
        $.each(['show', 'hide', 'fadeOut', 'fadeIn'], function (i, ev) {
            var el = $.fn[ev];
            $.fn[ev] = function () {
                var result = el.apply(this, arguments);
                result.promise().done(function () {
                    this.triggerHandler(ev, [result]);
                })
                return result;
            };
        });
    })(jQuery);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment