addEventListener
Lesson 10 of 13 in Coddy's JavaScript DOM Methods course.
The function addEventListener() attaches an event listener to an element, allowing your code to react to user interactions or other events (like clicks, mouseovers, or form submissions), using this syntax:
element.addEventListener("actionType", functionToExecute);For example :
function onClick() {
alert("Hello!");
}
const button = document.querySelector("#btn");
button.addEventListener("click", onClick);The above code attaches a click event to the button element, and once the button is clicked, the onClick function will be fired!
It's also possible to write in short,
const button = document.querySelector("#btn");
button.addEventListener("click", () => {
alert("Hello!");
});Challenge
EasyYou are given HTML code that contains button and paragraph with ID message.
Using JavaScript only, change the text of this paragraph element to "Button Clicked!", once the button is clicked!
Try it yourself
<!DOCTYPE html>
<html>
<body>
<button>Click Me!</button><p id="message">Not Clicked Yet !!</p>
<script src="script.js"></script>
</body>
</html>All lessons in JavaScript DOM Methods
3DOM Methods II
querySelectorAlladdEventListenerinnerHTMLcreateElement and appendChildclassList toggle