JavaScript - DOM Events
JavaScript - DOM Events
The DOM events are actions that can be performed on HTML elements. When an event occurs, it triggers a JavaScript function. This function can then be used to change the HTML element or perform other actions.
Here are some examples of DOM events:
- Clickβ This event occurs when a user clicks on an HTML element.
- Loadβ This event occurs when an HTML element is loaded.
- Changeβ This event occurs when the value of an HTML element is changed.
- Submitβ This event occurs when an HTML form is submitted.
You can use the event handlers or addEventListener() method to listen to and react to the DOM events. The addEventListener() method takes two arguments: the name of the event and the function that you want to be called when the event occurs.
The DOM events are also referred as Document Object Model events. It is used to interact with the DOM elements and manipulate the DOM elements from JavaScript when any event occurs.
Letβs look at the below examples of DOM events.
The onclick Event Type
This is the most frequently used event type which occurs when a user clicks the left button of his mouse. You can put your validation, warning etc., against this event type.
Example
Try the following example.
The ondblclick Event Type
We use the βondblclickβ event handler in the code below with theelement. When users double click the button, it calls the changeColor() function.
In the changeColor() function, we change the color of the text. So, the code will change the textβs color when the user double-clicks the button.
Example
The onkeydown Event Type
We used the βkeydownβ event in the code below with the <input> element. Whenever the user will press any key, it will call the customizeInput() function.
In the customizeInput() function, we change the background color of the input and the input text to red.