0

I have that kind of code to append an li element to a given ul with a fancy effect, then I call a function whose behavior depends on the # of children of that ul :

$(li).hide().appendTo("#ul-authors").show("blind");
toggleIfNeeded();

...

function toggleIfNeeded() {
  if ($("#ul-authors > li").length === 1) {
     doSomething();
  } else {
     doSomethingElse();
  }
}

The problem is, when toggleIfNeeded is called, the new li does not seem to exist yet, since the effect is not totally performed. If I remove the effect, it works correctly.

How can I do that ? I guess I need some sort of a timer, but that would be asynchronous (I don't want to block the app for a fancy effect) or, even better, a way to tell "call that function when the effect is performed".

I don't have the possibility to change 1 with 0 in the above since the code can be called in other contexts where no effect is involved.

2
  • 1
    do .show("blind", toggleIfNeeded) Commented Mar 1, 2013 at 13:43
  • Well, thanks @XuqiciAcerto, but my question was more precisely "how do we use callbacks in that context ?" Commented Mar 1, 2013 at 13:45

3 Answers 3

3

You can pass a callback to .show(). If you change

$(li).hide().appendTo("#ul-authors").show("blind");
toggleIfNeeded();

to

$(li).hide().appendTo("#ul-authors").show("blind", toggleIfNeeded);

then your function will be called automatically when the animation is finished.

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

Comments

1

the second parameter to show() can be a function where you can do what you want when animation ends

Comments

1

Try this

.show('<effect>', callbackFunction)

Comments

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.