Interview Questions

Launching Code on Document Ready

jQuery Interview Questions and Answers


(Continued from previous question...)

Launching Code on Document Ready

The first thing that most Javascript programmers end up doing is adding some code to their program, similar to this:

window.onload = function(){ alert("welcome"); }

Inside of which is the code that you want to run right when the page is loaded. Problematically, however, the Javascript code isn't run until all images are finished downloading (this includes banner ads). The reason for using window.onload in the first place is that the HTML 'document' isn't finished loading yet, when you first try to run your code.

To circumvent both problems, jQuery has a simple statement that checks the document and waits until it's ready to be manipulated, known as the ready event:

$(document).ready(function(){
// Your code here
});


Inside the ready event, add a click handler to the link:

$(document).ready(function(){
$("a").click(function(event){
alert("Thanks for visiting!");
});
});


Save your HTML file and reload the test page in your browser. Clicking the link on the page should make a browser's alert pop-up, before leaving to go to the main jQuery page.

For click and most other events, you can prevent the default behaviour - here, following the link to jquery.com - by calling event.preventDefault() in the event handler:

$(document).ready(function(){
$("a").click(function(event){
alert("As you can see, the link no longer took you to jquery.com");
event.preventDefault();
});
});

(Continued on next question...)

Other Interview Questions