D DevBrainBox

JavaScript Events

JS

What are JavaScript Events?

A JavaScript event is something that happens in the web page (like a user clicking a button or typing in a form) that JavaScript can listen for and respond to by running some code.

 var button = document.getElementById("myButton");

     // Add a click event listener
    button.addEventListener("click", function() {
     alert("Button was clicked!");
     });

Event Type

Each event has a specific type, indicating what happened. Common event types include:

Mouse Events:

  • click: When an element is clicked.
  • mouseover: When the mouse pointer moves over an element.
  • mouseout: When the mouse pointer moves off an element.
  • mousedown: When a mouse button is pressed down over an element.
  • mouseup: When a mouse button is released over an element.
  • mousemove: When the mouse pointer moves while over an element.

Keyboard Events:

  • keydown: When a key is pressed down.
  • keyup: When a key is released.
  • keypress: When a key is pressed and released (deprecated in favor of keydown/keyup for most cases).

Form Events:

  • submit: When a form is submitted.
  • change: When the value of an input, select, or textarea element changes.
  • focus: When an element gains focus.
  • blur: When an element loses focus.

Document/Window Events:

  • load: When a page or an image has finished loading.
  • DOMContentLoaded: When the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
  • resize: When the browser window is resized.
  • scroll: When the user scrolls the document.

Media Events:

  • play: When a video or audio starts playing.
  • pause: When a video or audio is paused.
  • ended: When a video or audio finishes playing.

Event Listener (or Event Handler)

An event listener is a JavaScript function that waits for a specific event to occur on a specific element. When the event happens, the function is executed.

a. Inline Event Handlers

<button onclick="alert('Button clicked!')">Click me</button>

b. Traditional DOM Event Handlers

const button = document.getElementById('myButton');
button.onclick = function() {
console.log('Button was clicked!');
};
const button = document.getElementById('myButton');

button.addEventListener('click', function() {
    console.log('Button clicked using addEventListener!');
});

// You can add multiple handlers for the same event type:
button.addEventListener('click', () => {
 alert('Another click!');
});

On this page