Embark on a journey of knowledge! Take the quiz and earn valuable credits.
Take A QuizChallenge yourself and boost your learning! Start the quiz now to earn credits.
Take A QuizUnlock your potential! Begin the quiz, answer questions, and accumulate credits along the way.
Take A Quiz
🎯 Introduction: Making
Your Web Pages Interactive
Web pages become truly interactive when they respond
to user actions. Whether it’s clicking a button, typing in a form, hovering
over a menu, or submitting data—JavaScript makes it all possible through event
handling.
This chapter will teach you:
🔍 What Are Events?
An event is an action that happens in the browser,
such as:
JavaScript can listen for these events and run a
function when they occur. This is called event handling.
🧠 Event Lifecycle Basics
🧰 Adding Event Listeners
🔹 Syntax:
javascript
element.addEventListener("eventType",
callbackFunction);
🔹 Example:
html
<button
id="btn">Click Me</button>
javascript
const
btn = document.getElementById('btn');
btn.addEventListener('click',
() => {
alert('Button clicked!');
});
📚 Common Events
Event Type |
Triggered When... |
Target |
click |
User clicks an element |
buttons, links, divs |
input |
User types
into input/textarea |
form fields |
submit |
A form is submitted |
<form> |
change |
A value
changes (select, checkbox) |
input, select |
mouseenter /
mouseleave |
User hovers in/out |
any element |
keydown / keyup |
Key is pressed
or released |
input,
textarea, document |
scroll |
Page or element is
scrolled |
window, containers |
🔧 Using Named Functions
Instead of writing functions inline, create reusable named
functions:
javascript
function
greet() {
console.log("Hello!");
}
btn.addEventListener("click",
greet);
✅ This makes code cleaner,
especially when reusing the same logic in multiple places.
🧪 Using the event Object
When an event occurs, JavaScript gives you access to an event
object.
🔹 Example:
javascript
btn.addEventListener("click",
function(event) {
console.log(event); // event type, target,
timestamp, etc.
console.log(event.target); // element clicked
});
📌 Common event
Properties:
Property |
Description |
event.target |
The actual DOM element
that triggered the event |
event.type |
Type of event
(e.g., "click", "input") |
event.preventDefault() |
Stops default behavior
(e.g., submitting a form) |
event.key |
Key pressed
during keyboard events |
event.clientX /
clientY |
Mouse coordinates on
screen |
✅ Preventing Default Actions
Use .preventDefault() to stop standard browser behavior:
html
<form
id="signupForm">
<input type="email" />
<button type="submit">Sign
Up</button>
</form>
javascript
const
form = document.getElementById('signupForm');
form.addEventListener('submit',
function(event) {
event.preventDefault();
alert('Form submission prevented for demo!');
});
⚙️ Removing Event Listeners
🔹 Syntax:
javascript
element.removeEventListener("event",
functionRef);
⚠️ You must use a named function
to remove it — anonymous functions can’t be removed.
🔹 Example:
javascript
function
sayHi() {
alert('Hi!');
}
btn.addEventListener('click',
sayHi);
//
Later...
btn.removeEventListener('click',
sayHi);
🎯 Event Delegation:
Handling Dynamic Elements
Event delegation lets you attach a single listener to a parent
element that monitors events from child elements.
🔹 Why Use It?
🔹 Example:
html
<ul
id="menu">
<li>Home</li>
<li>About</li>
</ul>
javascript
const
menu = document.getElementById('menu');
menu.addEventListener('click',
function(event) {
if (event.target.tagName === "LI")
{
alert(`You clicked:
${event.target.textContent}`);
}
});
🧠 Real-World Projects
with Events
🔸 1. Toggle Content
javascript
toggleBtn.addEventListener('click',
() => {
content.classList.toggle('visible');
});
🔸 2. Modal Window
javascript
openBtn.addEventListener('click',
() => modal.classList.remove('hidden'));
closeBtn.addEventListener('click',
() => modal.classList.add('hidden'));
🔸 3. Form Validation
javascript
form.addEventListener('submit',
e => {
if (email.value === "") {
e.preventDefault();
alert("Email is required!");
}
});
🔸 4. Live Search Filter
javascript
searchInput.addEventListener('input',
function() {
const keyword = this.value.toLowerCase();
items.forEach(item => {
item.style.display =
item.textContent.toLowerCase().includes(keyword) ? '' : 'none';
});
});
📊 Summary Table
Task |
Method |
Add click behavior |
.addEventListener('click',
fn) |
Prevent form submission |
event.preventDefault() |
Access target |
event.target |
Remove listener |
.removeEventListener() |
Delegate |
Parent
.addEventListener() + check event.target |
🧱 Best Practices
📍 Summary: What You’ve
Learned
You're now ready to use JavaScript to build fully
interactive and engaging user experiences!
A: The DOM (Document Object Model) is a
tree-like structure that represents your web page. JavaScript can access and
modify this structure to change elements, styles, content, and more—dynamically
and in real-time.
A: Not exactly. The DOM is a Web API provided by
the browser, but JavaScript interacts with it using built-in methods like
getElementById, querySelector, and addEventListener.
Use DOM methods like:
document.getElementById('id')
document.querySelector('.class')
document.querySelector('tag')
element.style.color
= "red";
element.style.backgroundColor
= "yellow";
Or better, toggle CSS classes:
element.classList.add('active');
element.classList.remove('hidden');
const
div = document.createElement('div');
div.textContent = "Hello!";
document.body.appendChild(div);
element.remove();
// Modern way
// OR
element.parentNode.removeChild(element);
// Older method
const
button = document.querySelector('button');
button.addEventListener('click',
function() {
alert('Button clicked!');
});
Please log in to access this content. You will be redirected to the login page shortly.
LoginReady to take your education and career to the next level? Register today and join our growing community of learners and professionals.
Comments(0)