Events
What is an Event?
Events are actions or occurrences that happen in the browser. JavaScript can "listen" for these events and run code in response. Events are what make web pages interactive.
Common examples of events:
- User clicks a button
- Mouse moves
- Keyboard is pressed
- Page finishes loading
- An input field changes value
- The browser window is resized
How Events Work
You select an element, then use addEventListener() to tell the browser: "When this event happens, run this function."
Example: Button Click Event
HTML:<button id="btn">Click Me</button>
JavaScript:
document.getElementById("btn").addEventListener("click", function() {
alert("Button was clicked!");
});
JavaScript waits for the user to click the button. When the click happens, the function runs and shows an alert.
More Common Events
Mouse Events:
- click
- mouseenter
- mouseleave
- dblclick
Keyboard Events:
- keydown
- keyup
- keypress
Form Events:
- submit
- change
- input
Window Events:
- load
- resize
- scroll
Summary
Events are user or browser actions that JavaScript can respond to. They allow you to create interactive and dynamic web pages.