Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Dom Event Listener in JavaScript

Dom Event Listener in JavaScript

? DOM Event Listener in JavaScript


What is an Event Listener?

An event listener is a function that runs when a specific event happens on a DOM element — like clicks, key presses, mouse moves, etc.


Adding Event Listeners

Use the method:

element.addEventListener(eventType, callbackFunction);
  • eventType: String name of the event, e.g., "click", "mouseover", "keydown"

  • callbackFunction: Function that runs when the event fires


Example: Click Event Listener

<button id="myBtn">Click Me</button><script>const button = document.getElementById("myBtn");button.addEventListener("click", function() {  alert("Button was clicked!");});</script>

Common Event Types

Event TypeDescription
clickMouse click
mouseoverMouse pointer moves over element
mouseoutMouse pointer leaves element
keydownKeyboard key pressed
keyupKeyboard key released
submitForm submitted
loadPage or image finished loading

Using Named Functions

function handleClick() {  console.log("Clicked!");}element.addEventListener("click", handleClick);

Removing Event Listeners

To remove an event listener, use:

element.removeEventListener("click", handleClick);

Note: You must pass the same function reference.


Example: Mouseover and Mouseout

const box = document.getElementById("box");box.addEventListener("mouseover", () => {  box.style.backgroundColor = "lightblue";});box.addEventListener("mouseout", () => {  box.style.backgroundColor = "white";});

Event Object

The callback receives an event object with info about the event:

element.addEventListener("click", (event) => {  console.log("Clicked at coordinates:", event.clientX, event.clientY);});

Summary

StepUsage
Add event listenerelement.addEventListener("click", callback)
Remove event listenerelement.removeEventListener("click", callback)
Use event object(event) => { /* event info */ }

Want me to show you event delegation, or how to handle keyboard events?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql