Events in HTML
? Events in HTML
Events are actions or occurrences that happen in the browser, which JavaScript can respond to. They make web pages interactive.
What are HTML Events?
Examples of events:
User actions like clicking, typing, hovering, submitting forms
Browser actions like page loading or resizing
Multimedia events like playing or pausing audio/video
Common HTML Event Attributes
You can add event handlers directly inside HTML tags using attributes like:
| Event | Description | Example |
|---|---|---|
onclick | When an element is clicked | <button onclick="alert('Hi')">Click me</button> |
onmouseover | When mouse hovers over element | <div onmouseover="this.style.color='red'">Hover me</div> |
onmouseout | When mouse leaves element | <div onmouseout="this.style.color='black'">Hover me</div> |
onchange | When input value changes | <input onchange="alert('Changed!')"> |
onload | When page or image loads | <body onload="init()"> |
onsubmit | When form is submitted | <form onsubmit="return validate()"> |
Example: Button Click Event
<button onclick="alert('Button clicked!')">Click Me</button>When the user clicks the button, an alert box appears.
Using JavaScript to Add Events (Better Practice)
<button id="myBtn">Click Me</button><script> const btn = document.getElementById('myBtn'); btn.addEventListener('click', () => { alert('Button clicked!'); });</script>Common Event Types
| Category | Examples |
|---|---|
| Mouse | click, dblclick, mouseover, mouseout, mousedown, mouseup |
| Keyboard | keydown, keyup, keypress |
| Form | submit, change, focus, blur |
| Window | load, resize, scroll |
| Media | play, pause, ended |
Want to learn how to create custom event handlers or handle multiple events in a cleaner way?