Hi
Can someone please tell me why does the following code snippet does NOT work
http://jsbin.com/izuzud/1/edit
But the following works?
http://jsbin.com/efujar/1/edit
The code is exactly the same same except the position.
| SitePoint Sponsor |



Hi
Can someone please tell me why does the following code snippet does NOT work
http://jsbin.com/izuzud/1/edit
But the following works?
http://jsbin.com/efujar/1/edit
The code is exactly the same same except the position.
Browsers execute code immediately as it becomes available. That means that in your first snippet, you're trying to select the button before the browser has reached the button markup.
"Folks who know what they're doing make complexity seem simple."



In the first snippet, the click event is never attached, because there's no button yet to attach it to.
"Folks who know what they're doing make complexity seem simple."



Yes, but only if the element you're selecting exists in the DOM. In your first snippet, you're trying to select the button before the browser has reached the markup, so the button isn't in the DOM yet.
"Folks who know what they're doing make complexity seem simple."



Because that delays your code from executing until the DOM has been fully loaded.
"Folks who know what they're doing make complexity seem simple."



I see but I thought the following two are the same:
AND$(document).ready(function(){
});
(function(){
})(jQuery);
Probably the second form you're thinking of is:
Code:jQuery(function ($) { });
"Folks who know what they're doing make complexity seem simple."



ok but the question is, are the following both the same?
$(document).ready(function(){
});
and
jQuery(function ($) {
});
Yes.
"Folks who know what they're doing make complexity seem simple."
Bookmarks