JavaScript Events (original) (raw)
Last Updated : 11 Dec, 2024
**JavaScript Events are actions or occurrences that happen in the browser. They can be triggered by various user interactions or by the browser itself.
HTML `
Click me`
- The onclick attribute in the calls the myFun() function when clicked.
- The myFun() function updates the
element with id="gfg" by setting its innerHTML to "GeeksforGeeks".
- Initially, the
is empty, and its content changes dynamically on button click.
Event Types
JavaScript supports a variety of event types. Common categories include:
- **Mouse Events: click, dblclick, mousemove, mouseover, mouseout
- **Keyboard Events: keydown, keypress, keyup
- **Form Events: submit, change, focus, blur
- **Window Events: load, resize, scroll
**Common JavaScript Events
Event Attribute | Description |
---|---|
onclick | Triggered when an element is clicked. |
onmouseover | Fired when the mouse pointer moves over an element. |
onmouseout | Occurs when the mouse pointer leaves an element. |
onkeydown | Fired when a key is pressed down. |
onkeyup | Fired when a key is released. |
onchange | Triggered when the value of an input element changes. |
onload | Occurs when a page has finished loading. |
onsubmit | Fired when a form is submitted. |
onfocus | Occurs when an element gets focus. |
onblur | Fired when an element loses focus. |
JavaScript ``
// Mouse Event
document.addEventListener("mousemove", (e) => {
console.log(Mouse moved to (${e.clientX}, ${e.clientY})
);
});
// Keyboard Event
document.addEventListener("keydown", (e) => {
console.log(Key pressed: ${e.key}
);
});
``
- The mousemove event tracks cursor movement.
- The keydown event captures key presses.
Event Handling Methods
**1. Inline HTML Handlers
Click Me
**2. DOM Property Handlers
let btn = document.getElementById("myButton");
btn.onclick = () => {
alert("Button clicked!");
};
**3. addEventListener() (Preferred)
btn.addEventListener("click", () => {
alert("Button clicked using addEventListener!");
});
addEventListener() is the most versatile and recommended method as it supports multiple event listeners and removal of listeners.
Event Propagation
JavaScript events propagate in two phases:
- **Capturing Phase****:** Event travels from the root to the target element.
- **Bubbling Phase****:** Event travels from the target element back to the root. JavaScript `
document.querySelector("div").addEventListener("click", () => { console.log("Div clicked"); }, true); // Capturing phase
button.addEventListener("click", (e) => { console.log("Button clicked"); e.stopPropagation(); // Stops propagation });
`
- Setting true in addEventListener makes it capture events during the capturing phase.
- stopPropagation() halts further propagation.
Event Delegation
Event delegation allows you to handle events efficiently by attaching a single listener to a parent element.
JavaScript ``
document.querySelector("ul").addEventListener("click", (e) => {
if (e.target.tagName === "LI") {
console.log(Clicked on item: ${e.target.textContent}
);
}
});
``
Events are delegated to list, reducing the need to add listeners to each list items.
Preventing Default Behavior
Certain elements have default actions (e.g., links navigating to URLs). Use preventDefault() to override them.
JavaScript `
document.querySelector("a").addEventListener("click", (e) => { e.preventDefault(); console.log("Link click prevented"); });
`
preventDefault() stops the link from navigating.
Practical Applications
1. Form Validation
HTML `
Form Validation
Submit`
2. Dynamic Content
HTML `
Dynamic Content
Add Element`
3. Interactive Lists
HTML `
Interactive Lists
- Interactive Item 1
- Interactive Item 2
- Interactive Item 3