Jquery interview questions: - When do we need Document.Readyevent ?
- By Shiv Prasad Koirala in .Net
- Jun 2nd, 2014
- 10856
- 0
HTML is loaded in to DOM by the browser in an interpreted manner. In other words every line is read from the HTML code and full finalDOM is created in memory after the last HTML statement is interpreted.
Now take the example of the below Jquery code which is accessing "txt1". At the line where Jquery is calling the textbox , the textbox is not loaded in DOM so this line will crash.
<body>
<script language=javascript>
$("#txt1").val("Hello Jquery");->Txt1 not loaded in DOM
</script>
<input type="text" id="txt1" />
</body>
This is where "document.ready"Jquery function comes to help and below is how we write it. The "ready" event fires when the complete DOM is loaded in memory. So now the below Jquery script will execute once all elements are loaded and thus will not have issues accessing the text box "txt1".
<script language=javascript>
$(document).ready(
function ()
$("#txt1").val("Hello Jquery");
}
);
</script>
Below is a nice video on Document.Ready from ShivprasadKoirala's site questpond. Below is the youtube link.
Shiv Prasad Koirala
Visit us @ www.questpond.com or call us at 022-66752917... read more