Previously, we've had to rely upon JavaScript's standard methods, especially the prompt() method, to gain information from the user. Forms, on the other hand, place graphical components directly on a Web page for use with JavaScripts. With this new method of user interaction comes a new model of programming -- event-driven programming.
In event-driven programming, an event is generated when something happens. For example, a user may press a button, which then generates a 'click' event. To trap events in JavaScript, an event handler is placed inside the HTML tag that defines the object. That event handler can then execute program instructions, or make a function call. For example, to create a button that calls the buttonFunction() when it is clicked, you would use the following code:
<input type="button" onclick="buttonFunction()">
This code creates a button and adds an event handler (onclick) in the object's tag. The event handler is followed by an equals sign and the appropriate statements enclosed in double quotation marks. Although event handlers can execute several statements (separated by semicolons), your code will be easier to understand if you make a call to a function inside the event handler. However, the following code would be perfectly legal:
<input type="button" onclick="if(prompt('Do you realise that you just pressed a button?') alert('Just checking!'); else alert('You really should be more careful!');">
The following is a list of the most commonly used event handlers in JavaScript, and a brief description of when they are generated:
Details on which events are generated by which objects are included with a description of each form object in this lesson's examples. For now, just familiarise yourself with JavaScript's events.