”;
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.
<html> <head> <script> function sayHello() { alert("Hello World") } </script> </head> <body> <p>Click the following button and see result</p> <form> <input type = "button" onclick = "sayHello()" value = "Say Hello" /> </form> </body> </html>
The ondblclick Event Type
We use the ”ondblclick” event handler in the code below with the
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
<html> <body> <h2 id = "text"> Hi Users! </h2> <button ondblclick="changeColor()"> Double click me! </button> <script> function changeColor() { document.getElementById("text").style.color = "red"; } </script> </body> </html>
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.
Example
<html> <body> <p> Enter charater/s by pressing any key </p> <input type = "text" onkeydown = "customizeInput()"> <script> function customizeInput() { var ele = document.getElementsByTagName("INPUT")[0]; ele.style.backgroundColor = "yellow"; ele.style.color = "red"; } </script> </body>