0

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

3 Answers 3

1

The DOM is not fully loaded .. Thats the reason it won't work..

So when you encase your code inside the DOM Ready handler 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..

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

1 Comment

I'm sorry but can you please elaborate
0

This is because $('#container').foo("outside"); is evaluated before the body is processed. $('#container') will return with a length of 0. This is demonstrated below.

$.fn.foo = function(somestring){
  var $this = this;
  $this.html(somestring);
}

$(function(){
    $('#container').foo("within function");
});

var element = $('#container');
console.log(element.length); //prints 0
element.foo("outside");

Comments

0

If the script is at the beginning of the page the rest of the HTML document has not been parsed yet, so the document looks empty to the script, so there is no #container yet.

$(function() { ... });

is (roughly) equivalent to

Wait till the whole HTML file is loaded and ready
Then execute function

so #container will be there and it will work. Another way to make it work would be to put the script below the rest of the page or at least below #container.

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.