JavaScript events

An event in JavaScript is a signal that shows something has occurred on a web page. The actions performed by the user, can be selecting a button, completing a form, or moving the mouse. When an event is triggered, JavaScript can be used to respond to the event by executing a block of code.

Examples of event used in JavaScript:

Click: This event is triggered when a user clicks an element on the page, such as a button or a link.

Submit: This event is triggered when a user submits a form on the page.

Keydown or Keyup: These events are triggered when a user presses or releases a key on the keyboard.

Load: This event is triggered when a web page finishes loading.

Example:

let button = document.getElementById("myButton"); button.addEventListener("click", function() 
{ console.log("Button clicked!"); });

In this example, you will use the addEventListener() method to add a click event listener to a button with the ID of myButton. When the user clicks on this button, the anonymous function passed as the second argument will be executed, and the message "Button clicked!" will be printed to the console using console.log().

Note that the addEventListener() method can be used to attach an event listener to almost any element on a web page, including the document object itself. Additionally, many JavaScript libraries and frameworks provide their own event handling mechanisms that can be used to simplify the process of working with events.

Last updated