JavaScript Events: types, lists, and examples

Events in JavaScript are browser actions or occurrences such as a user clicking a button, a page finishing loading, or a form being submitted. Event handlers, which are functions that are executed when an event occurs, are provided by JavaScript as a way to handle these events.

Types of events in JavaScript

There are multiple types of events in JavaScript, such as:

So let's describe these events one by one, briefly.

JavaScript mouse events

Several mouse events are available in JavaScript that can be used to react to user interaction with a web page. The following are a few of the most typical mouse events:

Mouse event Description
click When the mouse button is clicked (pressed and released) on an element, this event is triggered.
mouseover When the mouse pointer enters an element, the mouseover event is triggered.
mouseout This event is triggered when the mouse pointer leaves an element.
mousedown When the mouse button is pressed down on an element, this event is triggered.
mouseup Fires when the mouse button on an element is released.
mousemove This event is triggered when the mouse pointer moves over an element.

JavaScript mouse events example

Consider the following code as an example demonstrating the use of mouse events in JavaScript:

<!DOCTYPE html>
<html>
<body>
  <button id="myButton">Click me!</button>
  <p id="status"></p>

  <script>
    const button = document.querySelector('#myButton');
    const status = document.querySelector('#status');

    button.addEventListener('click', () => {
      status.textContent = 'Button clicked!';
    });

    button.addEventListener('mouseover', () => {
      status.textContent = 'Mouse over button!';
    });

    button.addEventListener('mouseout', () => {
      status.textContent = 'Mouse out of button!';
    });

    button.addEventListener('mousedown', () => {
      status.textContent = 'Mouse button down!';
    });

    button.addEventListener('mouseup', () => {
      status.textContent = 'Mouse button up!';
    });

    button.addEventListener('mousemove', () => {
      status.textContent = 'Mouse moving over button!';
    });
  </script>
</body>
</html>

The output that this example produces is:

We attach event listeners to the button element in this program to respond to various mouse events. When the user clicks the button with the mouse, the corresponding event listener function is called, which updates the text content of the status paragraph element to reflect the event.

JavaScript keyboard events

There are several keyboard events in JavaScript that you can use to detect when a user interacts with the keyboard on a web page. The following table lists and describes the keyboard events in JavaScript:

Keyboard event Description
keydown When a key on the keyboard is pressed, this event occurs. You can use it to determine which key was pressed by accessing the event object's "keyCode" or "which" property.
keyup When a key on the keyboard is released, this event occurs. You can use it to determine which key was released by accessing the event object's "keyCode" or "which" property.
keypress When a key on the keyboard is pressed and a character is generated, this event is triggered. You can use it to determine which character was generated by accessing the event object's "keyCode" or "charCode" property.
input Typing or pasting text in an input field triggers this event. It detects text entered into input fields.

JavaScript keyboard events example

Consider the following code as an example demonstrating the use of keyboard events in JavaScript:

<!DOCTYPE html>
<html>
<body>
  <label for="text-input">Enter some text:</label>
  <input id="text-input" type="text">
  <br><br>
  <div id="output"></div>

  <script>
    const textInput = document.getElementById('text-input');
    const outputDiv = document.getElementById('output');

    textInput.addEventListener('keydown', function(event) {
      outputDiv.innerHTML += `keydown: keyCode ${event.keyCode}<br>`;
    });

    textInput.addEventListener('keyup', function(event) {
      outputDiv.innerHTML += `keyup: keyCode ${event.keyCode}<br>`;
    });

    textInput.addEventListener('keypress', function(event) {
      outputDiv.innerHTML += `keypress: charCode ${event.charCode}<br>`;
    });

    textInput.addEventListener('input', function(event) {
      outputDiv.innerHTML += `input: ${event.target.value}<br>`;
    });
  </script>
</body>
</html>

The output that this example produces is:



This program generates a text input field for user input and a div for the program's output of information regarding keyboard events. The application adds input field event listeners for keydown, keyup, keypress, and input events.

When the user presses a key, the keydown event handler logs the pressed key's keyCode to the output div. The keyup event handler logs the keyCode of the released key when the user releases a key. When the user types a character, the keypress event handler logs the generated character's charCode. Finally, the input event handler logs the current value of the input field whenever the value of the input field changes.

JavaScript form events

Several events in JavaScript can be used to monitor changes and interactions with HTML forms. The following table lists and describes the form events in JavaScript:

Form event Description
submit When a form is submitted, either by clicking the submit button or by pressing the Enter key while a form element is in focus, this event is started.
reset When a user clicks the Reset button on a form, this event is started.
input When the value of a form input field changes, as happens when a user types into a text input or chooses an option in a select element, this event is triggered.
change When a form element's value changes and it loses focus, such as when a user selects a new option in a select element or unchecks a checkbox, this event is triggered.
focus When an element receives focus, such as when a user clicks on a form element or uses the keyboard to move to it, this event is triggered.
blur When an element loses focus, such as when a user clicks outside of a form element or uses the keyboard to navigate away from it, this event is launched.

JavaScript form events example

Consider the following code as an example demonstrating the use of form events in JavaScript:

<!DOCTYPE html>
<html>
<body>

   <form>
      <label for="name">Name:</label>
      <input type="text" id="name" name="name" required>
      <br>
      <label for="email">Email:</label>
      <input type="email" id="email" name="email" required>
      <br><br>
      <button type="submit">Submit</button>
      <button type="reset">Reset</button>
   </form>
   <p id="messagePara"></p>
   <script>
      const messagePara = document.getElementById("messagePara");
      const form = document.querySelector('form');
      const nameInput = document.querySelector('#name');
      const emailInput = document.querySelector('#email');

      form.addEventListener('submit', (event) => {
         event.preventDefault();
         messagePara.innerHTML = "Form submitted";
      });

      form.addEventListener('reset', () => {
         messagePara.innerHTML = "Form reset";
      });

      nameInput.addEventListener('input', () => {
         messagePara.innerHTML = "Name input changed";
      });

      emailInput.addEventListener('change', () => {
         messagePara.innerHTML = "Email input changed";
      });

      nameInput.addEventListener('focus', () => {
         messagePara.innerHTML = "Name input focused";
      });

      emailInput.addEventListener('blur', () => {
         messagePara.innerHTML = "Email input blurred";
      });
   </script>
   
</body>
</html>

The output should be:




The preceding example program generates a form, as you can see through the output above this paragraph, that includes two required input fields for name and email, as well as a submit and reset button. There is also a paragraph element with the ID "messagePara" in it.

In the preceding example, the JavaScript code monitors various form and input element events. The submit event prevents the form from submitting and changes the text of the "messagePara" element to "Form submitted." The "messagePara" element's text is changed to "Form reset" by the reset event. The name input element's input event modifies the text of the "messagePara" element to "Name input changed." The change event on the email input element changes the text of the "messagePara" element to "Email input changed."

Then, the focus event on the name input element modifies the text of the "messagePara" element to "Name input focused." The blur event on the email input element modifies the text of the "messagePara" element to "Email input blurred."

JavaScript window events

To recognize and react to window-related events, JavaScript offers a variety of events, which are listed and described in the following table:

Window event Description
load This event is triggered when the window's entire content, including images, scripts, and stylesheets, has been loaded.
resize When the size of the window changes, either by resizing the browser window or switching between portrait and landscape modes on a mobile device, this event occurs.
scroll This event occurs when the user scrolls the window's content using the scrollbar or touch gestures.
unload This event occurs just before the window is closed or navigated away from, giving you the opportunity to perform cleanup tasks or prompt the user to confirm their action.
beforeunload This event occurs before the unload event, allowing you to prompt the user to confirm their action or prevent the window from closing.
error This event is triggered when an error occurs while the window or its content is being loaded, such as a missing image or a syntax error in a script.

JavaScript window events example

Consider the following code as an example demonstrating the use of window events in JavaScript:

<!DOCTYPE html>
<html>
<body>

   <p id="outputText"></p>

   <script>
      const output = document.getElementById("outputText");

      window.addEventListener("load", function() {
         output.innerHTML = "Window is loaded.";
      });

      window.addEventListener("resize", function() {
         output.innerHTML = "Window is resized.";
      });

      window.addEventListener("scroll", function() {
         output.innerHTML = "Window is scrolled.";
      });

      window.addEventListener("unload", function() {
         output.innerHTML = "Window is unloaded.";
      });

      window.addEventListener("beforeunload", function(event) {
         event.preventDefault();
         output.innerHTML = "Window is about to be unloaded.";
      });

      window.addEventListener("error", function(error) {
         var x = error.message;
         x = "An error occurred: " + x;
         output.innerHTML = x;
      });
   </script>

</body>
</html>

The output should be:

You can adjust the window to see the change in the output text.

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!