Submodule 14.3: DOM events
DOM event handling
You are already familiar with events and how these can be used.
DOM gives us the ability to handle these events differently in order to be able to attach multiple actions in one event.
The way that we used to achieve this is by using the
The general syntax of this method is:
element.addEventListener(event, function, useCapture)
- The event parameter is required and can be any of the events that are listed on W3Schools reference of Events page. Note that you should not use the "on" word that we used with the "traditional" method. Thus onclick becomes click.
- The function parameter is also required and specifies the function that will be executed when the event occurs.
- The useCapture is not a required parameter and it is a Boolean value with false as a default value. It specifies whether the event will be happening at the capturing ( True) or the bubbling (False) phase. These two categories will be explained later.
Let's see an example of how we can use this method.
- Open your editor, create a new file and save it as
exersice14.3.1.htmlin the folder "yourNameWEB2JS".
- Copy the code below and paste it in the new file.
- Open the file in your browser and click the button to see the results.
As you can see, we attached 2 different actions to 1 event.