An event in JavaScript refers to any interaction or occurrence that can be detected by the browser, such as user actions (clicks, keypresses, etc.), or browser-related events (loading a page, resizing a window, etc.). JavaScript allows developers to create dynamic and interactive web pages by responding to these events.
click
: Triggered when an element is clicked.dblclick
: Triggered when an element is double-clicked.mouseover
: Triggered when the mouse pointer moves over an element.keydown
: Triggered when a key is pressed down.keyup
: Triggered when a key is released.submit
: Triggered when a form is submitted.change
: Triggered when the value of an input element is changed.load
: Triggered when the entire page has loaded.resize
: Triggered when the browser window is resized.To respond to an event, you need to attach an event listener to an element. An event listener is a function that gets executed when a specific event occurs.
javascript Copy code document.getElementById("myButton").addEventListener("click", function() { alert("Button clicked!"); });
In the example above, the event listener is attached to a button with the ID myButton
. When the button is clicked, an alert box is displayed.
You can also remove an event listener if it’s no longer needed.
javascript Copy code const myButton = document.getElementById("myButton"); function handleClick() { alert("Button clicked!"); } myButton.addEventListener("click", handleClick); // Remove the event listener myButton.removeEventListener("click", handleClick);
JavaScript events follow a hierarchy, known as event propagation. There are three phases:
You can control how events propagate using the stopPropagation()
method, which prevents further propagation of the event.