Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$(document).ready called inside an external function?

Tags:

jquery

I saw some jquery code on the Net somewhere, that took this form :

<script>            
function doSomething(message)
{   
    $(document).ready(function(){       
        alert(message);
        });
};
</script>

i.e. an external function ("doSomething") which has $(document).ready inside it. I'm confused because isn't the code under $(document).ready triggered when the DOM is loaded ? Its like having an event handler inside a function (?). Does this form of code make sense to anyone ? Thanks.

like image 538
Moe Sisko Avatar asked May 17 '11 07:05

Moe Sisko


2 Answers

It makes sense. $(document).ready registers an event handler that is fired when the DOM is fully loaded. The anonymous function that is passed to it, is that handler. If you register that handler after the DOM is loaded, it is fired immediately.

Javascript can be executed before the DOM is fully loaded, so what this function does, it actually registers messages that are not to be shown before the DOM is loaded. You can use this construct if you don't want the message to be displayed before the DOM is fully loaded.

like image 56
GolezTrol Avatar answered Sep 18 '22 01:09

GolezTrol


It was probably an error on the part of the original coder. You could do that, but you'd want to call doSomething pretty early on. Note that if the DOM is already ready when you call ready, jQuery will call the code, so it will happen either way, but it won't happen until someone, somewhere, calls doSomething. I can't see much purpose to the pattern, so unless you have some strong argument for using it — and given the question, I suspect you don't :-) — you can safely ignore it.

like image 27
T.J. Crowder Avatar answered Sep 20 '22 01:09

T.J. Crowder