0

I'm puzzled about the execution order of the following:

$('#home').live('pageinit',function(){
    $('#test').hide();

    $(function() { 
        alert('test1');
    });

    $('#button').click(function(event) {
        event.preventDefault();
    });
});

$('#home').live('pageshow',function(){
    alert('test3');
});

Here is the sequence:

  1. pageinit gets fired
  2. $('#test').hide() is executed
  3. $('#button').click()... is executed
  4. pageshow and alert('test3') go off
  5. alert('test1') is fired

Why isn't alert('test1') executed as number 3?

Thanks

chris
  • 649
  • 7
  • 26

1 Answers1

1

I am not sure whether any typo is there in the code but it should give you an error in the Inspect Element or Developer Console. Try enclosing the function like this:

(function() { 
   alert('test1');
})();

Check this fiddle with full source

dhaval
  • 7,611
  • 3
  • 29
  • 38
  • Yes, those were typos (fixed now). The actual code is correct but has that funny sequence problem. – chris Jun 26 '12 at 11:35
  • have you checked the fiddle, the sequence works as you want in the fiddle – dhaval Jun 26 '12 at 11:51
  • it works as you say! So what's the matter with using `$(function(){});` instead? What is the mechanism that "delays" its execution? – chris Jun 26 '12 at 14:28
  • Found the answer: http://stackoverflow.com/questions/3908724/what-event-does-jquery-function-fire-on It's a shorthand for `$(document).ready(function () { })` – chris Jun 26 '12 at 14:32