开发者

Writing callback functions

I'm using jQuery to write things like this:

    $('#current_image').fadeOut(function(){
        $('#current_image').attr('src',newImage).show();
    });

This is lovely, once the fadeOut has completed, the nested bit executes.

I'd like to make my own function here that would replace fadeOut. What would my function look like so tha开发者_开发问答t this code would work?

    $('#current_image').customFadeOut(function(){
        $('#current_image').attr('src',newImage).show();
    });


The key is just passing the function reference to the prototypal method you define, and binding that passed function to $.animate or whatever jquery animation function you use internally in that.

HTML:

<div id="blah" style="color:#fff; opacity:1; background:black; height:50px; position:relative; ">fsdljfdsjfds</div>
<a id="click" href="#">fjsd</a>

JS:

$.fn.customFadeOut = function (callback) {
    return $(this).animate({
        opacity: 0.25,
        fontSize: "3em",
        height: 'toggle'
    }, 5000, function () {
        callback.apply(this)
    });

}

$('#click').click(function () {
    $('#blah').customFadeOut(function () {
        alert('hi')

    })

})​

Live Demo

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜