Event is an action or a state of any action performed either by the user or by the browser. Example : click event, load event, mouseover event etc.
Using these events we can build many things because we now have control of the user's action. We can do something when the user does some action like clicking a button.
There are two terminology when we come across events in web development :
- Event Listener - Event listener is an object that listens to certain event
- Event Handler - Event handlers are generally a function that is invoked when a certain event occurs.
Listening to Event Using HTML Attribute
As we have seen in the previous section we can directly mention an event as an attribute to the HTML element and can trigger an event on that action. Example
You can also attach multiple events to the HTML element by the same method. Example
<p onevent1="doSomething()" onevent2="doSomethingElse()">
The addEventListener Method
addEventListener() method attaches an event listener to an HTML element.
The new event attached doesn't affect previous events. You can add multiple events to the element the same way as we did using the HTML attribute.
addEventListener() method you can add events to any DOM element not necessarily only HTML elements.
- element - It is HTML element we are attaching event to
- event - It is the name of event which you are interested in
- callback function - It is the function that run after event is triggered
- useCapture - This is a boolean value that specify weather to use event bubbling or event capturing. (This is an optional parameter and default value is false)
addEventListener() method do not use 'on' prefix in event name. like, instead of using 'onclick' just use 'click'.
Let's see a few examples.
You can also internal function as well in
Add Multiple Event Listener
addEventListener() method can add multiple same or different methods to the same element. Means we can add 2 or more that 2 event listeners for the same event.
Multiple different types of event can also be attached to the same HTML element using
Event Capturing And Event Bubbling
In Event bubbling when an event is fired for the element then its first run for the element then same event is fired for its parent element, then all the way up on other ancestor.
For example we have three nested elements MAIN > DIV > P, and a click event is fired on 'P' then it will fire for its parent 'DIV' and then for 'MAIN'.
Example: Event Bubbling
Remove Event Listener
Event listening can also be removed from any HTML element or object.
To remove the event listener use
Example: Remove Event Listener