JavaScript Events
An event is something that happens in the browser.
Examples:
- User clicks a button
- User types into an input
- Mouse moves
- Form is submitted
- Keyboard key is pressed
- Page loads
- Window is resized
JavaScript can listen for these events.
onclick
Example:
<button id="btn">Click Me</button>
const button = document.querySelector("#btn");
button.onclick = function() {
alert("Button clicked!");
};
This works, but addEventListener() is generally preferred.
addEventListener()
Syntax:
element.addEventListener("event", function() {
// code
});
Example:
const button = document.querySelector("#btn");
button.addEventListener("click", function() {
alert("Hello!");
});
Common Events
Click Event
<button id="btn">Change Text</button>
<h1 id="title">Original Text</h1>
const button = document.querySelector("#btn");
const title = document.querySelector("#title");
button.addEventListener("click", function() {
title.textContent = "Text Changed!";
});
This is a basic example of dynamic UI manipulation.