When I use methods that "append" data to existing elements using prototype/jquery, is it a good practice to wrap such logic inside document.observe("dom:loaded", foo)
/$(document).ready(foo)
functions?
views:
57answers:
2
+1
A:
Well, considering referencing elements before DOM/window ready will not work unless it's the html
element or you are injecting it after the element in the markup directly, yes it's the only way to really get it done.
<!doctype html>
<html>
<head>
<script>alert( document.getElementById('foo') );</script>
</head>
<body>
<p id="foo"></p>
</body>
</html>
The above would fail and return null.
meder
2010-07-06 09:57:34
That's understandable, but if i move the script right after the closing p tag, will that still work?
Salman A
2010-07-06 10:25:41
Yes, that's what I meant by "you are injecting it after the element in the markup directly"
meder
2010-07-06 15:43:40
+1
A:
Without a ready/loaded event, your code won't fire unless it's at the bottom of the page. This is because the elements don't exist when the code gets read from the <head>
section (which executes before the body).
Try this:
$("body").animate({'background-color', '#ff0000'}, 2000);
And then try this:
$(document).ready(function() {
$("body").animate({'background-color', '#ff0000'}, 2000);
});
You'll see what I mean :)
Marko
2010-07-06 10:02:00