Lesson 46 - Handling Events in JavaScript
JavaScript allows you to create interactive web pages by responding to user actions like clicks, key presses, form submissions, and more. This is done using event handling.
What are Events?
Events are actions that happen in the browser, such as:
- Clicking a button
- Typing in an input field
- Hovering over an element
- Submitting a form
JavaScript provides ways to listen for these events and run custom code when they occur.
Using addEventListener()
The recommended way to handle events is by using addEventListener()
.
Syntax
element.addEventListener("event", function);
element
: The HTML element to listen for events on.event
: The type of event (e.g.,"click"
,"mouseover"
).function
: The function to execute when the event occurs.
Example 1: Click Event
<button id="btn">Click Me</button>
<script>
let button = document.getElementById("btn");
button.addEventListener("click", function() {
alert("Button was clicked!");
});
</script>
- Clicking the button triggers an alert.
Example 2: Mouseover Event
<p id="text">Hover over me!</p>
<script>
let text = document.getElementById("text");
text.addEventListener("mouseover", function() {
text.style.color = "red";
});
text.addEventListener("mouseout", function() {
text.style.color = "black";
});
</script>
- The text turns red when hovered over and black when the mouse leaves.
Example 3: Keypress Event
<input type="text" id="nameInput" placeholder="Type something">
<p id="output"></p>
<script>
let input = document.getElementById("nameInput");
let output = document.getElementById("output");
input.addEventListener("keyup", function() {
output.textContent = "You typed: " + input.value;
});
</script>
- As you type, the text updates dynamically.
Example 4: Adding Multiple Event Listeners to the Same Element
let btn = document.getElementById("myButton");
btn.addEventListener("mouseover", () => {
console.log("Mouse is over the button!");
});
btn.addEventListener("click", () => {
console.log("Button was clicked!");
});
- The button listens for both
mouseover
andclick
events.
Example 5: Removing an Event Listener
Use removeEventListener()
to detach an event listener.
function sayHello() {
console.log("Hello!");
}
let btn = document.getElementById("myButton");
btn.addEventListener("click", sayHello);
// Remove the event listener after 5 seconds
setTimeout(() => {
btn.removeEventListener("click", sayHello);
console.log("Event listener removed!");
}, 5000);
- After 5 seconds, clicking the button won't trigger
"Hello!"
.
Try Your Hand
- Create a button that changes the page background color when clicked.
- Create a text input that converts all entered text to uppercase.
- Add an event that displays an alert when the page is fully loaded.
Key Takeaways
addEventListener()
allows handling multiple events per element.- Use
"click"
,"mouseover"
,"keyup"
, and many more event types. - Events make web pages interactive and dynamic.