JavaScript HTML Events

Making web pages interactive with event handling

⚡ What are HTML Events?

HTML events are actions that happen to HTML elements, like clicking a button, moving the mouse, or typing in a text field. JavaScript can respond to these events to make web pages interactive.


<!-- Simple click event -->
<button onclick="alert('Hello World!')">Click Me!</button>
                                    

Try it:

Common HTML Events

👆

Click Events

Respond to mouse clicks

<button onclick="myFunction()">Click</button>
🖱️

Mouse Events

Track mouse movements

<div onmouseover="changeColor()">Hover me</div>
⌨️

Keyboard Events

Capture key presses

<input onkeyup="showValue()">
📝

Form Events

Handle form interactions

<form onsubmit="validateForm()">

🔹 Click Events Example

The most common event is the click event. Here's how to use it:

<!DOCTYPE html>
<html>
<body>

<h2 id="demo">Click the button to change this text</h2>
<button onclick="changeText()">Change Text</button>

<script>
function changeText() {
    document.getElementById("demo").innerHTML = "Text has been changed!";
}
</script>

</body>
</html>

Try it:

Click the button to change this text

🔹 Mouse Events

Mouse events let you respond to mouse actions:

<div 
    onmouseover="this.style.backgroundColor='lightblue'" 
    onmouseout="this.style.backgroundColor='white'"
    style="padding: 20px; border: 1px solid #ccc;">
    Hover over me!
</div>

Try it:

Hover over me!

🔹 Keyboard Events

Capture keyboard input with key events:

<input 
    type="text" 
    onkeyup="showLength(this.value)"
    placeholder="Type something...">
<p id="length">Character count: 0</p>

<script>
function showLength(text) {
    document.getElementById("length").innerHTML = 
        "Character count: " + text.length;
}
</script>

Try it:

Character count: 0

🔹 Event Listeners

A better way to handle events is using addEventListener():

<button id="myBtn">Click Me</button>

<script>
document.getElementById("myBtn").addEventListener("click", function() {
    alert("Button was clicked!");
});

// You can add multiple listeners
document.getElementById("myBtn").addEventListener("click", function() {
    console.log("Another action!");
});
</script>

Try it:

🧠 Test Your Knowledge

Which event is triggered when a user clicks on an HTML element?