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.


   
         
   

   

Click the following button and see result

The ondblclick Event Type

We use the 'ondblclick' event handler in the code below with the element. 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



   

Hi Users!

The onkeydown Event Type

We used the 'keydown' event in the code below with the 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



   

Enter charater/s by pressing any key

Advertisements