05.01.2013 Views

hide - Understanding jQuery

hide - Understanding jQuery

hide - Understanding jQuery

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Only variables and events should be initialized inside $(document).ready, not functions.<br />

Though, this is not a rule! However, if you do that, certain things will occur that will prevent<br />

you from using the function in the global scope. In other words, function definitions are limited<br />

to the scope they are defined in, just like variables. We know that a scope is any place in<br />

your JavaScript program delimited by the { ... } brackets.<br />

I have received a question from one of my newsletters subscribers about defining a function<br />

inside $(document).ready(). It is an event that takes place after all DOM (all HTML elements)<br />

are physically loaded into the web page... so essentially what happens is that a function is defined<br />

inside the anonymous function that runs when this DOM event occurs. The function is<br />

now limited to the scope of the anonymous function attached to that event. Let’s take a look:<br />

<br />

$(document).ready(function()<br />

{<br />

function a() { alert(‘hello’); }<br />

a(); // here it works, because it was defined in the same scope<br />

}<br />

// But here it produces an error -<br />

// The function a() cannot be called outside of the scope it is defined in.<br />

a(); // error: undefined function<br />

<br />

In order to remedy this problem, we stick to defining all functions outside of the event This<br />

means they will become available to call from the entire program, even within $(document).<br />

ready... as well as throughout the whole scope of the program, the global scope.<br />

<br />

function a() { alert(‘hello’); } // let’s define the function in the global scope, instead.<br />

$(document).ready(function()<br />

{<br />

a(); // here it works<br />

}<br />

a(); // the function now works here as well<br />

<br />

20

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!