👂Event Listeners
An event listener is a procedure in JavaScript that waits for an event to occur — like a user clicking a button, hovering, typing, or scrolling.
It allows your web page to respond to user interactions dynamically.
🧠 Why Use Event Listeners?
To make websites interactive and responsive
To execute code only when a specific event happens
To separate JavaScript logic from HTML markup
element.addEventListener(event, callbackFunction);🔹 Parameters:
event: Type of event to listen for (e.g.,"click","keydown","mouseover")callbackFunction: Function to execute when the event occurs
🔍 Example: Click Event
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Button Click Example</title>
</head>
<body>
<button id="btn">Click Me</button>
<script>
const button = document.getElementById('btn');
button.addEventListener('click', function () {
alert('Button clicked!');
});
</script>
</body>
</html>📝 When the user clicks the button, an alert box appears.
🔁 Commonly Used Events
Event Name | Triggered When... |
|---|---|
| Element is clicked |
| Double click |
| Mouse moves over element |
| Mouse leaves the element |
| Key is pressed down |
| Key is released |
| Form is submitted |
| Form element changes |
| Page or element is scrolled |