Event Handling in JavaScript
Definition:
Event handling in JavaScript is the process of detecting and responding to user actions (called
events) on a webpage — such as clicks, mouse movements, key presses, or form submissions.
JavaScript allows you to assign event handlers (functions) to HTML elements that execute
automatically when a specific event occurs.
Common Events:
Event Type Description
onclick Triggered when an element is clicked
onmouseover Triggered when the mouse pointer moves over an element
onmouseout Triggered when the mouse leaves an element
onchange Triggered when an input field’s value changes
onkeyup / onkeydown Triggered when a key is pressed/released
onsubmit Triggered when a form is submitted
onload Triggered when the page finishes loading
Syntax:
You can handle events in three main ways:
1. Inline Event Handling (Inside HTML Tag)
<button onclick="alert('Button Clicked!')">Click Me</button>
2. Using JavaScript Property
<button id="myBtn">Click Me</button>
<script>
[Link]("myBtn").onclick = function() {
alert("Button was clicked!");
};
</script>
3. Using addEventListener() (Recommended Way)
<button id="btn">Click Me</button>
<script>
[Link]("btn").addEventListener("click", function() {
alert("Event handled using addEventListener()");
});
</script>
Example: Mouse Events
<!DOCTYPE html>
<html>
<body>
<h3 id="text">Hover over this text!</h3>
<script>
let text = [Link]("text");
[Link]("mouseover", function() {
[Link] = "red";
[Link] = "Mouse is over me!";
});
[Link]("mouseout", function() {
[Link] = "black";
[Link] = "Hover over this text!";
});
</script>
</body>
</html>
Output:
When you hover over the text, its color changes to red and the message updates. When you
move the mouse out, it returns to normal.
Example: Keyboard Event
<input type="text" id="inputBox" placeholder="Type something...">
<p id="output"></p>
<script>
[Link]("inputBox").addEventListener("keyup", function() {
[Link]("output").innerText = [Link];
});
</script>
Output:
Whatever you type appears live below the input box.