Skip to content
GitHub

Handling Events in JavaScript

Switch to Zen Mode

Here are some common event types:

  • Mouse events: Click, mouseover, mouseout, mousedown, mouseup, etc.
  • Keyboard events: keydown, keyup, keypress
  • Form events: submit, change, input, focus, blur
  • Document events: load, DOMContentLoaded, resize, scroll
  • Media events: play, pause, ended, volumechange
  • Other events: touch events, focus, and blur events


There are three main ways to add event handlers to an element in JavaScript:


Inline event handling involves adding event handler code directly to HTML elements as event attributes. This approach is generally not recommended due to maintainability issues.

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

  • This method allows setting a function as an event handler for an element.
  • If there is already an event handler assigned using onclick, it will be overwritten by a new one.
const button = document.querySelector("button");
button.onclick = function() {
alert("Button clicked!");
};
javascript

Syntax:

element.addEventListener(event, function, useCapture);
javascript
  • event: The name of the event (e.g., “click”, “keydown”).
  • function: The callback function to be executed when the event occurs.
  • useCapture (optional): A boolean that specifies whether the event should be captured during the capturing phase (true) or the bubbling phase (false, default).

Example: of using addEventListener to handle a button click event:

const element = document.getElementById("elementId");
element.addEventListener("click", function() {
alert("Element clicked!");
});
javascript

  1. element: This refers to a specific DOM (Document Object Model) element on the web page, like a button, a div, or any HTML element you can interact with. You would typically get this element using methods like document.getElementById(), document.querySelector(), etc.

  2. addEventListener: This is a method that attaches an event handler (a function) to the specified element. It listens for an event (like a mouse click, key press, etc.) and runs a function when that event happens.

  3. 'event': This is a string that specifies the type of event you’re listening for. Common events include:

    • 'click': Triggered when the element is clicked.
    • 'mouseover': Triggered when the mouse pointer is over the element.
    • 'keydown': Triggered when a key is pressed down.
    • 'submit': Triggered when a form is submitted.
  4. function: This is the callback function that will run when the event occurs. The function contains the code you want to execute when the event is triggered. It can be an anonymous function, like:

    function() {
    console.log("Element clicked!");
    }
    js

    Or a named function, like:

    function handleClick() {
    console.log("Element clicked!");
    }
    js

To remove an event listener, you can use the removeEventListener() method. This is useful for cleaning up or detaching events when they’re no longer needed.

const button = document.querySelector("button");
function clickHandler() {
alert("Button clicked!");
}
button.addEventListener("click", clickHandler);
button.removeEventListener("click", clickHandler);
javascript

Events in JavaScript can propagate in two phases:

Before bubbling, events go from the root down to the target element:

root → ... → grandparent → parent → element
plaintext

You can control which phase the event listener will be active in by setting the useCapture, the third parameter of addEventListener:

element.addEventListener('click', handler, true); // true enables capturing phase
// Or with the options object syntax:
element.addEventListener('click', handler, { capture: true });
javascript

The event bubbles back up from the target element to the outermost element. By default, events “bubble” up from the target element to the root of the document:

element → parent → grandparent → ... → root
plaintext

You can prevent this bubbling behavior by using event.stopPropagation() in your event handler.


When an event is triggered, an event object is automatically passed to the event handler function. This object contains useful information about the event, such as the target element, the type of event, and other details.

button.addEventListener('click', function(event) {
console.log(event); // The event object
console.log(event.type); // "click"
console.log(event.target); // The element that triggered the event
});
javascript
  • event.type: The type of event (e.g., “click”, “keydown”)
  • event.target: The element that triggered the event
  • event.currentTarget: The element that the event handler is attached to
  • event.timeStamp: The time when the event occurred
  • event.bubbles: Boolean indicating if the event bubbles up the DOM tree
  • event.cancelable: Boolean indicating if the event can be canceled
  • event.defaultPrevented: Boolean indicating if preventDefault() has been called

Event-specific properties:

  • Mouse events: clientX, clientY, pageX, pageY, screenX, screenY, button, buttons, altKey, ctrlKey, shiftKey, metaKey
  • Keyboard events: key, code, keyCode (deprecated), altKey, ctrlKey, shiftKey, metaKey
  • Form events: Form elements often include properties like value, checked, selected, etc.
  • event.preventDefault(): Prevents the default browser behavior for the event
  • event.stopPropagation(): Stops the event from bubbling up the DOM tree
  • event.stopImmediatePropagation(): Stops both bubbling and prevents other handlers on the same element
  • preventDefault(): Prevents the default behavior of the event. For example, prevent a form from submitting.

    form.addEventListener("submit", function(event) {
    event.preventDefault();
    console.log("Form submission prevented.");
    });
    javascript
  • stopPropagation(): Stops the event from propagating (bubbling or capturing).

    element.addEventListener("click", function(event) {
    event.stopPropagation();
    console.log("Event propagation stopped.");
    });
    javascript

You can create and dispatch your own events using the CustomEvent constructor.

Example: Creating and Dispatching Custom Events
// Create a custom event
const myEvent = new CustomEvent('myCustomEvent', {
detail: { message: 'Hello from custom event!' },
});
// Add a listener
document.addEventListener('myCustomEvent', (e) => {
console.log(e.detail.message);
});
// Dispatch the event
document.dispatchEvent(myEvent);
javascript

Event TypeDescription
Mouse Events
clickFired when a mouse button is clicked.
dblclickFired when a mouse button is double-clicked.
mousedownFired when a mouse button is pressed down.
mouseupFired when a mouse button is released.
mousemoveFired when the mouse pointer moves.
mouseenterFired when the mouse enters an element.
mouseleaveFired when the mouse leaves an element.
mouseoverFired when the mouse pointer hovers over an element or its child elements.
mouseoutFired when the mouse pointer leaves an element or its child elements.
Keyboard Events
keydownFired when a key is pressed down.
keyupFired when a key is released.
keypressFired when a key is pressed and released (deprecated).
Form Events
submitFired when a form is submitted.
inputFired when an input field changes.
changeFired when an input element changes (like a select dropdown menu).
Window Events
loadFired when the page is fully loaded.
resizeFired when the window is resized.
scrollFired when the page is scrolled.