JavaScript Events
JavaScript events are actions that happen in the browser, such as a user clicking a button, hovering over an element, or typing in a field. JavaScript can respond to these events and execute code.
Events make web pages interactive by allowing user actions to trigger specific functions.
Click Event
The click event occurs when a user clicks on an element like a button.
<!DOCTYPE html>
<html>
<body>
<p id="clickDemo"></p>
<button onclick="showMessage()">Click Me</button>
<script>
function showMessage() {
document.getElementById("clickDemo").innerHTML = "Button Clicked!";
}
</script>
</body>
</html>
Try this code
Mouse Over Event
The mouseover event occurs when the user moves the mouse over an element.
<!DOCTYPE html>
<html>
<body>
<p id="hoverDemo">Hover over this text</p>
<script>
document.getElementById("hoverDemo").onmouseover = function() {
this.innerHTML = "Mouse Over!";
}
</script>
</body>
</html>
Try this code
Mouse Out Event
The mouseout event occurs when the mouse leaves an element.
<!DOCTYPE html>
<html>
<body>
<p id="outDemo">Move mouse away</p>
<script>
document.getElementById("outDemo").onmouseout = function() {
this.innerHTML = "Mouse Out!";
}
</script>
</body>
</html>
Try this code
Input Event
The input event occurs when the user types in an input field.
<!DOCTYPE html>
<html>
<body>
<input type="text" id="inputBox" placeholder="Type something">
<p id="inputDemo"></p>
<script>
document.getElementById("inputBox").oninput = function() {
document.getElementById("inputDemo").innerHTML = this.value;
}
</script>
</body>
</html>
Try this code
Change Event
The change event occurs when the value of an input element is changed.
<!DOCTYPE html>
<html>
<body>
<select id="selectBox">
<option>HTML</option>
<option>CSS</option>
<option>JavaScript</option>
</select>
<p id="changeDemo"></p>
<script>
document.getElementById("selectBox").onchange = function() {
document.getElementById("changeDemo").innerHTML = this.value;
}
</script>
</body>
</html>
Try this code
Why Events are Important
- They make websites interactive
- They respond to user actions
- They improve user experience
- They are used in forms, buttons, and animations