Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What determines the execution order of methods in jQuery chains?

HTML Code

<div id="foo">
    <h1>foo</h1>
    <p>Pellentesque habitant morbi tristique.</p>
</div>
<div id="bar">
    <h1>bar</h1>
</div>

jQuery Code

$('#bar').click(function () {
    $('#foo p').hide('slow').appendTo('#bar').show('slow');
})

Expected Result

When #bar is clicked

  1. hide the p element in #foo
  2. append p to #bar
  3. show p which is now a child of #bar

Actual Result

  1. append p to #bar
  2. hide the p element in #foo
  3. show p which is now a child of #bar

Questions

  • What determines the execution order of methods in jQuery chains?
  • How can I ensure that each event completes before the next starts?
like image 301
Beau Smith Avatar asked Oct 21 '09 00:10

Beau Smith


1 Answers

To ensure you execute something AFTER an effect like hide or show, use a callback. http://docs.jquery.com/Effects/show#speedcallback

To Add:

Vincent is right, the execution is actually

  1. start hiding the p element in #foo (SLOWLY)
  2. append p to #bar (in a snap)
  3. start showing p which is now a child of #bar (SLOWLY)

What you saw was the result of the effect

  1. append p to #bar (executed)
  2. hide the p element in #foo (COMPLETED)
  3. show p which is now a child of #bar (COMPLETED)
like image 129
o.k.w Avatar answered Oct 13 '22 22:10

o.k.w