HI everyone! I am back with another blog in my Javascript scries. Today we are going to see about a wonderful Javascript method which is very comfortable to use. If you know this already, well good to go! Otherwise it will help you so much, particularly if you going to study DOM(Document Object Model). Let's see,
Introduction
When I first started learning JavaScript, getting element and making them interactive or dynamic using DOM is a very big task for me. That time I found a method addEventListener()
. It's like giving life to your HTML elements — making them respond when the user interacts with them.
What is an Event?
In JavaScript, an event is an action that occurs in the browser, like:
- Clicking a button
- Typing in a textbox
- Moving the mouse
- Submitting a form
JavaScript can listen for these events and react when they happen.
What is addEventListener()
?
addEventListener()
is a built-in method that lets you attach a function to run when an event occurs on a specific HTML element.
Basic Syntax:
Javascript
element.addEventListener("eventType", functionToRun);
-
element
: The HTML element you want to interact with -
"eventType"
: The event name as a string (like"click"
,"mouseover"
,"input"
) -
functionToRun
: The code that should run when the event happens
Example 1
Here is my code, by this you will get better knowledge,
What happens here:
- When you click the button, the browser shows an alert.
- The function inside addEventListener() runs only when the click event happens.
Here, I use addEventListener()
, instead of using onclick = "Text change"
.
Example 2:
In this programming I used onclick = "Text change"
,
For this you may got What I am trying to said.
Real-Life Use Cases
- Show a success message when a form is submitted
- Change image when a button is clicked
- Toggle dark/light mode
- Validate input when typing
So that's it guys. When I understood addEventListener()
, JavaScript felt less scary. I hope this post helps you feel the same. Try using it in your own projects, buttons, forms, sliders — and you’ll see how useful it is.
If you liked this post or have questions, feel free to drop a comment! Will see in my next blog.
Top comments (0)