Make your websites interactive - respond to clicks, hovers, key presses, and more!
Events are actions that happen in the browser - like clicking a button, moving the mouse, typing on the keyboard, or submitting a form.
Common Events:
• click - User clicks an element
• mouseover - Mouse enters an element
• mouseout - Mouse leaves an element
• keypress - User presses a key
• submit - Form is submitted
• change - Input value changes
The modern way to handle events in JavaScript:
// Get the element
var button = document.getElementById("myButton");
// Add event listener
button.addEventListener("click", function() {
console.log("Button was clicked!");
});
Respond to key presses:
document.addEventListener("keypress", function(event) {
console.log("Key pressed: " + event.key);
});
var form = document.getElementById("myForm");
form.addEventListener("submit", function(event) {
event.preventDefault(); // Stop form from submitting
console.log("Form submitted!");
});
The event object contains information about the event:
button.addEventListener("click", function(event) {
console.log(event.target); // Element that was clicked
console.log(event.type); // "click"
console.log(event.clientX); // Mouse X position
console.log(event.clientY); // Mouse Y position
});
Challenge: Build Interactive Features!
📚 Class 8 - Advanced JavaScript • Make It Interactive! 🚀