Is it possible to get some kind of event notifciation when an element has faded in using jQuery? I.e. if there was a 'fadeInEvent' I would try something like
$('elements').delegate('selector', 'fadeInEvent', function() {
alert('someId has faded in');
});
I know that there is a callback function for jQuery.fadeIn(), e.g.
$('#someId').fadeIn('fast', function() {
alert('callback when someId has faded in');
});
but I would rather use an event solution if possible. I also did some prototyping using :visible
, but it returns true
before the fade in has completed.
Is it possible to get some kind of event notifciation when an element has faded in using jQuery? I.e. if there was a 'fadeInEvent' I would try something like
$('elements').delegate('selector', 'fadeInEvent', function() {
alert('someId has faded in');
});
I know that there is a callback function for jQuery.fadeIn(), e.g.
$('#someId').fadeIn('fast', function() {
alert('callback when someId has faded in');
});
but I would rather use an event solution if possible. I also did some prototyping using :visible
, but it returns true
before the fade in has completed.
4 Answers
Reset to default 12You can trigger a custom event in the callback:
$("#someId").fadeIn("fast", function() {
$(this).trigger("fadeInComplete");
});
The event will bubble up the DOM tree like most events, so you can capture it on any of the ancestor elements with on
(jQuery 1.7+), bind
or delegate
:
$("#someAncestor").on("fadeInComplete", function() {
//Element has finished fading in.
});
You could ensure that in each callback you pass into the fadeIn method you raise the appropriate event, or you could monkey patch the exising jQuery fadeIn method to always raise a fadeInEvent in the callback, eg:
(function($) {
var jQueryFadeIn = $.fn.fadeIn;
var newFadeIn = function(speed, callback) {
var newCallback = function() {
if (callback) {
callback.apply(this, arguments);
}
$(this).trigger('fadeInComplete');
};
jQueryFadeIn.apply(this, speed, newCallback);
};
$.fn.fadeIn = newFadeIn;
})(window.jQuery);
Maybe you can use Jquery-UI effects and use the callback argument
Nothing worked for me, so my solution was to hack fadeIn function and run custom trigger
var oldFadeIn = $.fn.fadeIn;
$.fn.fadeIn = function(){
$(this).trigger('fadeInComplete');
return oldFadeIn.apply( this, arguments );
}
Then simply bind it on whatever you need
$('.some_element').on('fadeInComplete', function(){
// do some magic here
});