Events in JavaScript
Understanding Events in JavaScript
1. What are Events?
An event is an action that happens in the browser. JavaScript can detect these actions and run code in response.
Common examples:
- Clicking a button
- Typing in a textbox
- Moving the mouse
- Submitting a form
JavaScript uses event listeners to respond to these actions.
2. Common JavaScript Events
| Event | Description |
|---|---|
| click | When the user clicks an element |
| input | When the user types in a field |
| change | When an input value changes |
| mouseover | When the mouse moves over an element |
| submit | When a form is submitted |
Example:
document.getElementById("btn").addEventListener("click", function(){
alert("Button clicked!");
});
3. Event Handling with Functions
function showMessage(){
alert("Welcome Students!");
}
<button onclick="showMessage()">Click Me</button>
4. Event Listener Method
Using addEventListener() is the modern and recommended way.
let button = document.getElementById("btn");
button.addEventListener("click", function(){
console.log("Button clicked");
});
5. Real-Life Example: Interactive Color Changer
This application changes the background color when the user clicks a button.
index.html
<!DOCTYPE html>
<html>
<head>
<title>Color Changer</title>
</head>
<body>
<h2>Interactive Color Changer</h2>
<button id="redBtn">Red</button>
<button id="greenBtn">Green</button>
<button id="blueBtn">Blue</button>
<script src="app.js"></script>
</body>
</html>
Run Code
app.js
let redBtn = document.getElementById("redBtn");
let greenBtn = document.getElementById("greenBtn");
let blueBtn = document.getElementById("blueBtn");
redBtn.addEventListener("click", function(){
document.body.style.backgroundColor = "red";
});
greenBtn.addEventListener("click", function(){
document.body.style.backgroundColor = "green";
});
blueBtn.addEventListener("click", function(){
document.body.style.backgroundColor = "blue";
});
Run Code
6. How This Example Works
- The user clicks a color button.
- JavaScript listens for the click event.
- When the button is clicked, the background color of the page changes.
7. Practice Exercise
Create a Light Bulb Switch application.
Features:
- A button to turn the light ON
- A button to turn the light OFF
Hint: Change the image of a bulb using JavaScript.
8. What Students Learned
- What events are
- Common browser events
- Handling events with functions
- Using
addEventListener()
Next Chapter
Chapter 10: ES6 Features in JavaScript with Real-Life Example: Student Grade Analyzer