Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery fadeIn event?

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.

like image 485
matsev Avatar asked Dec 05 '11 14:12

matsev


2 Answers

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.
});
like image 179
James Allardice Avatar answered Oct 21 '22 12:10

James Allardice


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);
like image 4
Rich O'Kelly Avatar answered Oct 21 '22 12:10

Rich O'Kelly