views:

75

answers:

1

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 that this code would work?

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

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

meder
Can't "function(){ callback.apply(this); }" be replaced by "callback"?
Vincent Robert
Yes, but maybe there needs to be general functionality for all `customFadeOut`s in addition to the `callback` so this way is more flexible yet more explicit. I think a demonstration of more capabilities is better than succinctness. In addition, what if someone calls `customFadeOut` without a function? Then it would fail, and you know how there are a lot of jQuery noobs who don't know JS and/or don't read APIs properly to know you'd have to feed an argument :p
meder