What are DOM Events in JavaScript?


DOM Events are actions or occurrences that happen in the browser — like clicking a button, pressing a key, hovering with a mouse, or submitting a form. JavaScript can listen to these events and respond using event listeners.



1. Basic Event Syntax – addEventListener()


Example:

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

Output: A pop-up alert shows when the button is clicked.



2. Common DOM Events

Event Type Triggered When…
click An element is clicked
mouseover Mouse hovers over an element
mouseout Mouse leaves an element
keydown A keyboard key is pressed
keyup A key is released
submit A form is submitted
change An input field value changes
load Page finishes loading


3. Event with Arrow Function

document.querySelector("#myBtn").addEventListener("click", () => {
console.log("Arrow function triggered");
});


4. Handling Input with change Event

<input type="text" id="nameInput" />
<script>
document.getElementById("nameInput").addEventListener("change",
function () {
alert("You changed the input!");
});
</script>


5. Form Submit Example

<form id="myForm">
<input type="text" placeholder="Enter name" />
<button type="submit">Submit</button></form>
<script>
document.getElementById("myForm").addEventListener("submit", 
function (e) {
e.preventDefault(); // Prevent page reload
alert("Form submitted!");
});
</script>


6. Mouse Events

const box = document.querySelector("#hoverBox");
box.addEventListener("mouseover", () => {
box.style.backgroundColor = "yellow";
});
box.addEventListener("mouseout", () => {
box.style.backgroundColor = "lightgray";
});


7. Keyboard Events

document.addEventListener("keydown", (event) => {
console.log("Key pressed:", event.key);
});


8. Using this Inside Event Listener

<button onclick="changeText(this)">Click Me</button>
<script>
function changeText(element) {
element.textContent ="Clicked!";
}
</script>