What is Event Handling
An event is triggered any time a user interacts with a web page. This event can be anything from a user clicking somewhere on the page to loading a webpage.
Whenever an event occurs on a web page the browser notifies the system; specific event handler functions listen for their respective events and when those events are triggered they execute the block of code written inside them. The code written inside the function contains all the actions that need to be performed in response to the event being fired.
Note: I will use the console to demonstrate the examples present in this post.
What are the different types of events?
The onclick() event handler is used to listen to the click events on a webpage. Whenever the user clicks on an HTML element on a webpage, its respective onClick() event handler is triggered.
Now Let’s look at an example to have a clear understanding of the click event handler:
<button onClick="clickEvent()" value="Button 1">Button 1</button>
<button onClick="clickEvent()" value="Button 2">Button 2</button>
console.log(event.target.value + " is clicked");
We have a web page with two buttons i.e. Button 1 and Button 2:
If we click on any of these buttons, their respective onclick() event handler is triggered which prints a message onto the console.
The onfocus() event gets triggered when an element gets or loses focus:
For example, in the code snippet given below, the “focusEvent()” method is called on the onfocus() event in the input tag:
The onkeydown() event is triggered when a key is pressed by the user:
For example, in the following code, the “keyDownEvent()” function is called on the “onkeydown” event, and the alert message is shown in the function definition:
alert("Pressed a key");
The onLoad() event is triggered right after the web page has been successfully loaded.
For example, in the code snippet given below, a simple alert message is displayed on the onload() event in the body tag: