11

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.

matsev
  • 32,104
  • 16
  • 121
  • 156

4 Answers4

12

You 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.
});
James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • Thanks, this solves my problem. I use `bind` for now, because the project is currently using jQuery 1.6.4. – matsev Dec 05 '11 at 15:23
4

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);
Syffys
  • 570
  • 5
  • 21
Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114
  • I'm getting `this.animate is not a function`, like this is not properly mapped within the fadeIn replacement. Not sure how to work through this, any idea ? – Syffys Sep 28 '20 at 14:52
  • 1
    @Syffys thanks, I think that your edit addresses this case? – Rich O'Kelly Sep 29 '20 at 09:46
0

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
});
KubiQ
  • 91
  • 4
0

Maybe you can use Jquery-UI effects and use the callback argument

dafi
  • 3,492
  • 2
  • 28
  • 51