SA-21/06, C-11, Asapur, Varanasi, UP support@kamaldnp.com +91 8318013442
JavaScript
1. JavaScript Tutorial for Beginners — Learn JS from Scratch 2. Where to Put JavaScript Code — Head, Body or .js File 3. JavaScript Output Methods — alert, innerHTML, console.log 4. JavaScript Syntax Explained — Statements & Rules 5. JavaScript Comments — How to Write // and /* */ 6. JavaScript Variables — var, let, const Explained 7. JavaScript Operators — Arithmetic, Comparison, Logical 8. JavaScript Data Types — string, number, object, array 9. JavaScript Functions Tutorial — Parameters & Return Values 10. JavaScript Objects — Properties, Methods & this Keyword 11. JavaScript Scope — Global, Local & Block Scope Explained 12. JavaScript Events — addEventListener with Examples 13. JavaScript Strings — Methods, slice, replace & Templates 14. JavaScript Numbers — parseInt, toFixed, NaN Explained 15. JavaScript Arrays — Create, Read, push, pop & More 16. JavaScript Array Methods — map, filter, forEach, find 17. JavaScript Date Object — new Date(), getFullYear & More 18. JavaScript Math Object — random, round, floor, ceil 19. JavaScript if else — Conditions with Examples 20. JavaScript switch Statement — case, break, default 21. JavaScript for Loop — for, for...of, for...in Examples 22. JavaScript while Loop — while & do...while Explained 23. JavaScript Type Conversion — Number, String, Boolean 24. JavaScript try catch — Error Handling with finally 25. JavaScript JSON — stringify & parse with Examples 26. JavaScript Arrow Functions — => Syntax & this 27. JavaScript Classes — Constructor & Objects Explained 28. JavaScript Promises & async/await Explained Simply 29. JavaScript DOM Tutorial — Find & Change Page Elements 30. JavaScript Form Validation Tutorial with Examples 31. JavaScript Fetch API Tutorial — fetch() with Examples 32. JavaScript localStorage — setItem, getItem Explained 33. JavaScript Timers — setTimeout & setInterval Examples 34. JavaScript Regular Expressions — test() & match() Guide 35. JavaScript Debugging — console.log & Fixing Errors
Final Test — Certificate ₹10
Try this code live
Lesson 12 of 35

JavaScript Events — addEventListener with Examples

4 min read · Free · No login needed

An event is something that happens on a page: a click, a mouse moving over a button, a key pressed, a form submitted, a page finishing loading. JavaScript's whole job is to listen for events and answer them. Without events, a page is a poster — you can only look at it. With events, it becomes a conversation: the user does something, JavaScript answers.

Diagram — see how it fits together
Diagram: JavaScript Events

Every event has a name and a place where it happens. A click on a button is a click event on that button. Moving the mouse over a picture is a mouseover event on that picture. Your code says: "when this event happens on this element, run this function."

Handling events with HTML attributes

The simplest way is to write the handler straight into the HTML, with an attribute like onclick. The value is the JavaScript to run when the event fires.

<button onclick="sayHello()">Say Hello</button>

This works and is easy to read, which is why you will see it in many examples — including this course. But it mixes JavaScript into your HTML, and each element can only have one handler per event this way.

addEventListener — the better way

The professional way is addEventListener. You keep your HTML clean and attach the handler from your script instead. You can attach several handlers to the same event, and you can remove one later with removeEventListener.

let btn = document.getElementById("orderBtn");
btn.addEventListener("click", function() {
  alert("Your chai is on its way!");
});

Notice there is no "on" in the event name here — it is "click", not "onclick". The function you pass is called the event handler or listener, and it runs every time the event fires.

Note: The handler function receives an event object as its first argument, usually written as event or e. It tells you useful things: event.target is the element that was clicked, event.key is the key that was pressed. You do not need it for every handler, but it is there whenever you do.

Common events to know

  • click — the user clicks an element. The most used event of all.
  • mouseover / mouseout — the mouse enters or leaves an element. Good for hover effects.
  • keydown / keyup — a key is pressed or released. Good for live search and games.
  • submit — a form is submitted. Good for checking the form before it is sent.
  • load — the page has finished loading. Good for code that must wait for the whole page.
Tip: Put your <script> at the end of the <body>, or wait for the load event, before you call getElementById. If the script runs before the button exists on the page, getElementById returns null and addEventListener fails. This is one of the most common beginner errors in all of JavaScript.

Common mistakes

  • Attaching a listener before the element exists — the script runs before the HTML is read, so getElementById finds nothing.
  • Writing addEventListener("onclick", ...) — the event name is "click", without the "on".
  • Calling the handler while attaching it — addEventListener("click", sayHello()) runs it immediately; write sayHello without brackets to pass the function itself.
  • Forgetting that one element can have many listeners — with addEventListener they all run, in the order they were added.

Remember

  • An event is something that happens: click, hover, keypress, submit, load.
  • onclick="..." in HTML is the simple way; addEventListener("click", ...) is the professional way.
  • The handler receives an event object — event.target is the element that was clicked.
  • The user does something, JavaScript answers — every click is a conversation.

Example explained

  • onclick="orderChai()" — the simple way: the button's HTML carries its own handler, which runs orderChai() on click.
  • document.getElementById("surpriseBtn").addEventListener("click", ...) — the professional way: the script finds the button and attaches a handler to it, keeping the HTML clean.
  • onmouseover="this.style.backgroundColor='orange'" — a hover event that changes the box's colour while the mouse is over it.
  • onmouseout="this.style.backgroundColor='white'" — the matching event that changes the colour back when the mouse leaves.
  • document.getElementById("msg").innerHTML = ... — every handler writes its message into the same paragraph, so the visitor sees what just happened.

Example

Example
<!DOCTYPE html>
<html>
<head>
<title>Events — Click and Hover</title>
<style>
body { font-family: Verdana, sans-serif; background-color: #fff8e1; }
h1 { color: #b45309; }
button { background-color: #e13611; color: white; padding: 10px 18px; border: none; margin: 4px; }
#hoverBox { background-color: white; border: 2px solid #b45309; padding: 20px; width: 300px; text-align: center; }
</style>
</head>
<body>

<h1>Events — Click and Hover</h1>
<button onclick="orderChai()">Order Chai (onclick)</button>
<button id="surpriseBtn">Surprise Me (listener)</button>
<div id="hoverBox" onmouseover="this.style.backgroundColor='orange'" onmouseout="this.style.backgroundColor='white'">Hover over this box</div>
<p id="msg">Click a button or hover over the box.</p>

<script>
function orderChai() {
  document.getElementById("msg").innerHTML = "Your chai is on its way!";
}
document.getElementById("surpriseBtn").addEventListener("click", function() {
  document.getElementById("msg").innerHTML = "Surprise! Free kulhad chai today.";
});
</script>

</body>
</html>

Output

Output — how it looks in the browser
Output of JavaScript Events — addEventListener with Examples

Try it yourself — live editor

Change the code below and press Run to see the result instantly. No file to save, no login needed.

Result

Frequently asked questions

The questions learners ask most about this lesson — read the question, then open it to see the answer.

1. What is an event in JavaScript?

Something that happens on a page: a click, a mouse hover, a keypress, a form submit, or a page finishing loading.

2. Why is addEventListener better than onclick in HTML?

It keeps HTML clean and lets you attach several handlers to the same event, while onclick mixes JavaScript into HTML and allows only one handler.

3. What is event.target?

The handler receives an event object, and event.target is the element the event actually happened on.

Why learn this yourself — and not just ask AI?

AI can write code for you, but it cannot think for you. When you learn HTML yourself, your brain builds the real skill: you understand why a page looks the way it does, you can fix it when it breaks, and you can answer it in an exam or an interview without help. That is the skill that gets you a job — not a copied answer.

Get certified — just ₹10

Finish all 35 lessons, pass the test (80%), pay ₹10 and get your certificate.

Take the test

Prefer watching? Video courses teach the same topics step by step.

Go further with a full course

Free tutorials teach you the basics. Our paid courses add live projects, mentorship and a certificate.

AI Prompt Engineering Webinar 2026
View
CapCut Mobile Video Editing Course Beginner to Advance
₹99
View
Ethical Hacking & Cyber Security Workshop
View
Browse all courses
JavaScript — Lessons
1. JavaScript Tutorial for Beginners — Learn JS from Scratch 2. Where to Put JavaScript Code — Head, Body or .js File 3. JavaScript Output Methods — alert, innerHTML, console.log 4. JavaScript Syntax Explained — Statements & Rules 5. JavaScript Comments — How to Write // and /* */ 6. JavaScript Variables — var, let, const Explained 7. JavaScript Operators — Arithmetic, Comparison, Logical 8. JavaScript Data Types — string, number, object, array 9. JavaScript Functions Tutorial — Parameters & Return Values 10. JavaScript Objects — Properties, Methods & this Keyword 11. JavaScript Scope — Global, Local & Block Scope Explained 12. JavaScript Events — addEventListener with Examples 13. JavaScript Strings — Methods, slice, replace & Templates 14. JavaScript Numbers — parseInt, toFixed, NaN Explained 15. JavaScript Arrays — Create, Read, push, pop & More 16. JavaScript Array Methods — map, filter, forEach, find 17. JavaScript Date Object — new Date(), getFullYear & More 18. JavaScript Math Object — random, round, floor, ceil 19. JavaScript if else — Conditions with Examples 20. JavaScript switch Statement — case, break, default 21. JavaScript for Loop — for, for...of, for...in Examples 22. JavaScript while Loop — while & do...while Explained 23. JavaScript Type Conversion — Number, String, Boolean 24. JavaScript try catch — Error Handling with finally 25. JavaScript JSON — stringify & parse with Examples 26. JavaScript Arrow Functions — => Syntax & this 27. JavaScript Classes — Constructor & Objects Explained 28. JavaScript Promises & async/await Explained Simply 29. JavaScript DOM Tutorial — Find & Change Page Elements 30. JavaScript Form Validation Tutorial with Examples 31. JavaScript Fetch API Tutorial — fetch() with Examples 32. JavaScript localStorage — setItem, getItem Explained 33. JavaScript Timers — setTimeout & setInterval Examples 34. JavaScript Regular Expressions — test() & match() Guide 35. JavaScript Debugging — console.log & Fixing Errors
Final Test — Certificate ₹10

🤖 KAMALDNP AI Assistant

Ask about courses, website & more

Hi! I'm KAMALDNP AI Assistant. Ask me about our courses, website features, or anything else! 😊
Please wait 5s...
🤖 KAMALDNP Assistant ✕

Request human callback:

🔐 Login Required
✕

Please log in to download. You will stay on this page after logging in!

New here? Register now →