7

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();
    });

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Can't "function(){ callback.apply(this); }" be replaced by "callback"?
Yes, but maybe there needs to be general functionality for all customFadeOuts 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.