Koder
Koder

Reputation: 27

adding a callback to this function

Would someone mind giving me a hand and help me out by taking a look at this function and explaining how i could add and execute a callback function after last element is finished fading in. I'm not sure how i'm suppose to fit it in or rework the code to get the result i'm looking for.

code is here Fiddle

Thank you

Upvotes: 0

Views: 74

Answers (2)

David Thomas
David Thomas

Reputation: 253318

It's not exactly a pretty answer, but one approach is simply to assess whether there is, or is not, a next() element and re-call the function or perform a different action:

function elFadeIn(elem) {
    elem.fadeIn('slow', function() {
        if ($(this).next().length) {
            elFadeIn($(this).next());
        }
        else {
            alert('finished');
        }
    });
}​

JS Fiddle demo.

And a slightly prettier way of writing that would be:

function elFadeIn(elem, callback) {
    elem.fadeIn('slow', function() {
        var next = $(this).next(),
            action = next.length ? elFadeIn(next) : alert('finished!');
    });
}​

JS Fiddle demo.

Upvotes: 2

pimvdb
pimvdb

Reputation: 154838

Using a callback is nothing more than passing a function as an argument, and calling that function at a certain time. As a side note, I suspect you want all .item elements, but .next doesn't care about the original selector. http://jsfiddle.net/4Pvmq/6/

$(function(){
    elFadeIn('.item', function() {
        alert("done");
    });
});

function elFadeIn(selector, callback) {
    var $items = $(selector);

    // this is the function that's going to be called recursively
    (function fade(i) {
        var $elem = $items.eq(i);

        if($elem.length) {  // there is an element
            $elem.fadeIn('slow', function() {  // fade it
                fade(i + 1);
            });
        } else {  // no elements left
            callback();
        }
    })(0);  // start with first
}

Upvotes: 1

Related Questions