I just don\'t get it. I searched and searched but for this I just can\'t figure out what\'s \"right\".
There are three examples.
1) Fiddle 1.0
Here we have
A lot of what you're seeing is because of jsFiddle's very surprising default setting, which is to wrap the code in the script pane in an onload
handler. So your code is wrapped in a function and no longer at global scope (which is where functions need to be if you use onclick
-style attributes). You can change this with the drop-down box on the left (the second one, under the list of libraries and scripts). Change it to "no wrap" to have unwrapped code.
You're not (by far!) the first to be bit by this surprising default.
Answering your main question:
when has a function to be in $(document).ready()
If you control where the script
tags loading your script go, you basically never have to use ready
; instead, just make sure your script
tags are at the end of the HTML, just before the closing
.
You can use ready
, of course. The reason for doing so is to make sure that all the DOM elements have been created before your code runs. But if you put your script
tag at the end, that's already true. You can still define your functions outside of the ready
handler (if you want them to be globals), but if you're using ready
, you would call them from the ready
handler so the elements exist.
FWIW, I would avoid using onclick
-style attributes for hooking up event handlers, primarily because they require you to create global functions. I prefer to avoid creating any global symbols when I can avoid it.
The general form I'd recommend: