0

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

asked Sep 21, 2012 at 17:35

2 Answers 2

2

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.

answered Sep 21, 2012 at 17:39
Sign up to request clarification or add additional context in comments.

3 Comments

+1 Beat me to it lol, I'd personally store $(this).next() in a var to don't create 2 jQuery objects and transverse the DOM twice for the same thing - jsfiddle.net/4Pvmq/3
Yeah, I was working towards that with the second example. And thank you! =)
Updated version is just perfect. =]
1

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
}
answered Sep 21, 2012 at 17:43

2 Comments

really well setup and what i'm looking for. thanks. One other questions though. Is it possible to reverse the order in this and fade out from the last element all the way to the first?
@Koder: Using .fadeOut, i - 1 and starting with $items.length - 1 should work.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.