I am constructing a page which uses jQuery to assign event handlers. Now I am assigning onclick events to functions but does the page run the script and then construct the HTML or does the page construct HTML and then run the script?
<script type="text/javascript">
function opinionbyid(popinionid){
$.post("index.php", {"opinionid":popinionid}, function(data){
var data2 = JSON.parse(data);
$(".opinion").html(data2.opinion);
$(".note").html(data2.note);
}, "json");
}
function loginform() { $(".middle").html($(".loginform").html()); }
function registerform() { $(".middle").html($(".registerform").html()); }
function opinionpostform() {};
$("#loginbutton").click(function(){
//UNSURE, MAYBE I SHOULD DO IT IN $.ready(function(){ HERE }))
});
</script>
like
$.ready(function(){
$("#loginbutton").click(function(){
// code...
});
})
so far I habitually used script tags in the head section. this is why I think I should use $.ready() because assigning handlers to obects is done after objects are loaded, in jquery’s documentation example.
<!DOCTYPE html>
<html>
<head>
<style>
p { color:red; margin:5px; cursor:pointer; }
p.hilite { background:yellow; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p>First Paragraph</p>
<p>Second Paragraph</p>
<p>Yet one more Paragraph</p>
<script>
$("p").click(function () {
$(this).slideUp();
});
$("p").hover(function () {
$(this).addClass("hilite");
}, function () {
$(this).removeClass("hilite");
});
</script>
</body>
</html>
after solution edit:
In the end, I thought “why am I handling the events with script anyway?” now I am using
onClick="dosomething()"
on button properties. no need to complicate anything.
HTML pages are parsed from the top down. Parsing JS blocks the parsing of HTML until the JS has been executed:
If you’re attaching your scripts just before
</body>, then you wont need to wait fordocument.readybecause you’re essentially already there.If you’re attaching your scripts within the
<head>then you’ll need to wait fordocument.readybecause none of the DOM will have been parsed when the code is executed.If you’re making modular code, and you’re not sure where it’ll be added, wait for
document.readybefore binding so that it’s safe no matter where the script is added.If you’re working with dynamic content, or simply don’t want to add a
document.readyhandler, you can uselive(deprecated as of 1.7) oron:This format will delegate the event listener to the
documentobject which does exist at the time of execution. jQuery will handle the context behind the scenes to execute everything in the context of the selector provided in the second argument.As a side note, make sure to alias
jQueryto$before use if you plan on reusing the code with other libraries. Thedocument.readyaliasing shortcut is one of the best ways to do it:Alternatively, use a self-executing closure: