jQuery: How to call function when element shows
56,270
Solution 1
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().
Solution 2
The following code (adapted from http://maximeparmentier.com/2012/11/06/bind-show-hide-events-with-jquery/) will enable you to use $('#someDiv').on('show', someFunc);
.
(function ($) {
$.each(['show', 'hide'], function (i, ev) {
var el = $.fn[ev];
$.fn[ev] = function () {
this.trigger(ev);
el.apply(this, arguments);
return el;
};
});
})(jQuery);
Solution 3
It must be done in the show() method, in its post-callback:
$('#someDiv').show('slide',function(){
alert('example')
});
Solution 4
<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
<script>
$(document).ready(function(){
$("#jq_message").show(function(){
$("#jq_message").fadeOut(3000);
$("#div2").fadeOut("slow");
$("#div3").fadeOut(3000);
});
});
</script>
<div id="jq_message">
</div>
Author by
user1364684
Updated on March 10, 2020Comments
-
user1364684 about 4 years
I want to call a function when a div shows (after show).
Does anybody knows how could I do this? I try to use something like that:
$(#someDiv).bind('show',function(){ alert('example') });
But I don't sure if I do that from correct way or if it is possible or not achieve that. Any ideas?
-
NLemay over 10 yearsIt tried, and it doesn't seems to work. Did you manage to make it work once?
-
Brian Leishman about 9 yearsThis breaks chaining after
show()
orhide()
are called -
JellicleCat about 9 yearsThanks for the heads up, @BrianLeishman. I've made a change to preserve chaining and a plunker to test it: plnkr.co/edit/Yv5nnqBI2o23mitDQI86?p=preview
-
Rikaelus almost 9 yearsI still had a problem with the updated version with chaining, specifically with the Chosen library that seems to leverage it. The problems seemed to go away if I tweak it to be "return el.apply(this,arguments);" I think you're returning the original function instead of the response?
-
Ravinder Payal over 8 yearswhats the difference between your code snippet and code provided by OP $("#SF-pid-1").on('show',function(){ alert("Jai Ho"); }); tried to call this and this also have not worked
-
Clonkex over 6 yearsWhy is this the accepted answer? It's not even an answer to the question.
-
L. Alejandro M. over 4 yearsThis way you are not "waiting" for the event. It's useless, for example, in case of a modal window because you are showing it right now.
-
L. Alejandro M. over 4 yearsJquery mobile. Deprecated 1.4.0
-
kerstvo over 4 yearsBad idea to trigger custom events on random elements. If I have custom handler on some element for my custom event
show
, I don't want it triggers by someone else