I have a form with two text fields and a button. How can I tell when the user has clicked on to the document and not one of these three objects? I want to be able to put the focus back on the first text field when this happens.
When you click on one of your html form elements, the onclick event for that element fires, but the event also 'bubbles' up to the document level causing an onclick event in the document to fire as well. That means two onclick events occur when you click on one of your form elements: one for the element and one for the document. You can easily observe that 'bubbling' phenomenon by putting an alert() in their onclick event handlers.
The problem is: you can't distinguish between an onclick event that has bubbled up from one of your elements and reaches the document, and an onclick event that originated in the document. That means just setting the focus() when the document's onclick event fires will end up setting the focus() when you click on one of the form elements--yet you only want to set the focus() when the document is clicked. Therefore, you have to cancel event 'bubbling' when a user clicks on one of your elements. Then, the only time an onclick event will fire for the document is when the user clicks on the document. Try this:
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
//Assign event handler functions to the event after the page
//loads. You have to wait until after the page loads, so that when
//you refer to the html elements they exist:
document.onclick = set_focus;
document.getElementById("tb0").onclick = set_focus;
document.getElementById("tb1").onclick = set_focus;
document.getElementById("b1").onclick = set_focus;
//w3c and NN browsers automatically send the event as
//an argument to an event handler function, which I am catching and storing
//Keep the event from 'bubbling' up to the document:
if (!e) var e = window.event; //for IE which does not send the event
e.cancelBubble = true; //cancel bubbling in IE
if (e.stopPropagation) e.stopPropagation(); //cancel bubbling for w3c browsers
//Because the event handler function was 'registered' with the event,
//rather than being inserted inline in the html, inside an event handler
//function the 'this' keyword refers to the html element that was clicked: