In this Article we will understand the Different ways of Event handling that Javascript offers to us, but first, we need to understand what Event is ?
An Event is an action that occurs when user give some instruction as input or try to manipulates state of website. And the process of reacting to the events is called Event Handling. Javascript interacts with HTML by Event Handlers.
For example — when a user press a keyboard key or mouse click, the heading or text of a Website will change.
http://sh017.hostgator.tempwebhost.net/media/5bd9d997a17bb0ef66b59aeb011c21bcsource: giphy.com
There are many types of Events and their event handlers like :-
- Mouse Events : onclick, onmouseover, onmouseout, onmouseup, onmousedown etc.
- Keyboard Events : onkeyup and onkeydown.
- Document/Window events : onload, onunload, onresize etc.
- Form Events : onfocus, onsubmit, onblur, onchange etc.
Javascript offers 3 different ways to handle events.
- HTML event handlers.
- DOM level event handlers
- Event Listeners
HTML Event Handlers ( Inline Event )
In this, we assign an event handler with the function as an attribute in the HTML tag. But using HTML event handlers considered as a Bad practice because of the following reasons :
- Readability : Difficult to read when we have multiple event handlers on same element because Event handler code mixed with HTML code
- Timing Issue : If the element is loaded fully before javascript code , user starts interacting with it which in turn gives error.
DOM level event handlers
In this , we have to give our element an identity which could be an id or class. As compare to previous one, in this Scope of function can easily be controlled.
One Common point is We can have only 1 event handler per event type in both.
Event Listeners
In this method, We can use events by adding an event listener to an object. By this way we can handle wide range of events triggered by user.
In this we can have multiple event handlers per event type.
addEventListener()
– to register an event handler.removeEventListener()
– to remove an event handler.
Thanks For Reading, I hope you found this Article helpful.🙂