最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery fadeIn event? - Stack Overflow

programmeradmin2浏览0评论

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.

Share Improve this question asked Dec 5, 2011 at 14:34 matsevmatsev 33.8k17 gold badges125 silver badges168 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 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.
});

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
});
发布评论

评论列表(0)

  1. 暂无评论