DOM events in JavaScript
What is Event?
Events on the website are simply interacting on the browser. For example a mouse click, file loading on the browser or swiping the image left or right.
Now let us learn about the event handler function to create interactive websites.
1. Registering Event Handlers:
An event handler function is registered as a property attached to the DOM element being interacted with.
Check out the syntax:
Let’s break down the syntax:
- First, we accessed the DOM element by its id that is defined in the HTML file using: document.getElementById(‘targetElement’); and store it in eventTarget variable.
- Then we created the event handler property in this above syntax we are using click event which triggers when the user presses and releases a mouse button on a DOM element.
- Lastly, we assigned an event handler function to the property.
The event handler can also be registered as an HTML element but it is recommended to avoid inline JavaScript.
It is best practice to create named event handler function instead of anonymous functions. This way your code will remain organized.
Get Animesh’s stories in your inbox
Join Medium for free to get updates from this writer.
Here is an example of named event handler function:
Adding Event Handlers:
Like eventTarget.onclick = eventHandlerFunction; the eventTarget.addEventListener(‘click’, eventHandlerFunction); method is another alternative way for registering event handlers. An addEventListener function waits for a specific event to occur and respond to it. This method requires two arguments:
- The event type as a string in this case ‘click’.
- The event handler function.
Removing Event Handlers:
The .removeEventListener() the method is used to reverse the .addEventListener() method. This method stops the code from “listening” for an event to fire when it no longer needs to. .removeEventListener also passes two arguments:
- The event type as a string
- The event handler function
Pre-defined Event Object Properties:
There are predefined properties associated with the event objects you can call these properties to see information about the event.
- The .target property to access the element that triggers the event.
- .type property to access the name of the event.
- .timeStamp to access the time in millisecond passed since the document loaded.
Event Type:
Beyond the click event, there are all types of DOM events that can fire in a browser! It’s important to know most events in the DOM take place without being noticed because there are no event handlers connected to them. To explore more event types, check out the MDN reference:
All the mouse event that found in the MDN docs above link:
Thanks and Happy Coding!





