HTML and CSS Reference
In-Depth Information
Event Listeners
You have already encountered event listeners multiple times in this chapter. Event listeners are used to attach func-
tions to a particular event, such as a page load, mouse click, or key press.
There are two ways of creating event listeners. The first is to attach a function to an event that occurs on a JavaScript
object, using the following syntax. This should look somewhat familiar to you.
window.onload = function() {
// Do something.
Here an empty function block is attached to the onload event of the window object. This onload event is called
when the page loads. You don't necessarily have to use an empty function block here. If you have defined a function
in your JavaScript code you could use that too.
window.onload = sayHello(“Joe");
The second method for creating an event listener is to use the addEventListener() function. This function has
two parameters. The first is the event that should trigger the event listener and the second is a function that should be
executed when the event is triggered. The addEventListener() function should be called on an object as in the
following example.
In this example an alert dialog would be displayed to the user when they click the button with the ID btn .
Note the event parameter that is passed into the function block in the previous example. When the event is
triggered, details about the event will be passed to the function block through this parameter. You don't have to
define a parameter for the event data; it is optional.
You will be using event listeners many times in the remaining chapters of this topic, especially in Chapters 11 and 12
when you will use them to listen for button clicks and form submissions.
Let's write a little program that uses what you have learned here.
1. Create a new file in your text editor.
2. Save this file as example10-6.js .
3. Add the following JavaScript code to this file.
window.onload = function() {
var button = document.getElementById(“btn");
button.addEventListener(“click", function() {
Search WWH ::

Custom Search