开发者

Possible to attach handler to a slidedown event?

Is it possible to listen for a slidedown event on an particular element?

I was hoping it would be easy as:

 $("#element").slideDown();

 $('#element').bind('slideDown', function() {  
    alert(开发者_JAVA百科'Slidedown event fired');  
 });

Couldn't find "slideDown" as an event.

Is listening for such an event possible?


To do this sort of thing, I just add more semantic methods. So if you've got a menu and you want to trigger an event when you slide it down, instead do something like,

var menu = $('#menu');
menu.open = function() {
  menu.slideDown();
  menu.trigger('menuOpened');
};

Then just call menu.open() instead of menu.slideDown(). This approach is more readable and maintainable as you build other objects that interact with each other. Then if you choose to change your opening animation later (say, to fadeIn or something), you don't have to update everything that interacts with it.


With some help from Ben on method overriding I was able to add a trigger on the function call that you can bind to:

$(function(){
    ;(function($){
        var orig_slideDown = $.fn.slideDown;

        $.fn.slideDown = function(){
            $(this).trigger('slideDown');
            orig_slideDown.apply(this, arguments);
        };
    })(jQuery);

    $('.up').click(function(){
        $('div').slideUp();
    });
    $('.down').click(function(){
        $('div').slideDown();
    });
    $('div').bind('slideDown',function(){
        $('div').append($('<p>').text('Down Triggered'));
    });
});

<a href="#" class="up">Up</a> <a href="#" class="down">Down</a>
<div style="width:300px;height:200px;background-color:red;color:white;">
    <p>Hello, world!</p>
</div>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜