This might be a very basic question but I’m trying to understand this behavior
This is my javascript code. I want to know why second call to foo does not work. Here is the JSFiddle link
$.fn.foo = function(somestring){
var $this = this;
$this.html(somestring);
}
$(function(){
$('#container').foo("within function"); //this works
});
$('#container').foo("outside"); //this does not
The
DOM is notfully loaded .. Thats the reason it won’t work..So when you encase your code inside the
DOM Readyhandler it waits for the document to be loaded and then runs the code inside.This makes sure the element is available before any code is run on it..
When the
HTML document is parsed, it parses top down.So if the script is included in the head section , then the scripts are loaded first and then the HTML structure.. When you try to the run the code , it obviously won’t work cause the element was still not parsed..
So encasing that in the handler will make sure the element is available before calling the methods on them..