What are Inline Events?
Inline events are JavaScript code written directly inside HTML tags using onclick, onmouseover, etc.
Common inline events:
1<!-- Click event - runs when clicked -->
2<button onclick="alert('Button was clicked!')">Click Me</button>
3
4<!-- Mouse hover event - changes color when mouse enters -->
5<div onmouseover="this.style.backgroundColor='yellow'"
6 onmouseout="this.style.backgroundColor='white'">
7 Hover your mouse over me
8</div>
9
10<!-- Image error fallback - shows different image if original fails -->
11<img src="image-that-might-not-exist.jpg"
12 onerror="this.src='fallback-image.jpg'">
13
14<!-- Input focus events - changes border when clicked -->
15<input type="text"
16 onfocus="this.style.border='2px solid blue'"
17 onblur="this.style.border='1px solid gray'">
18
19<!-- Form submission - asks for confirmation -->
20<form onsubmit="return confirm('Are you sure you want to submit?')">
21 <button type="submit">Submit</button>
22</form>Common inline event attributes:
Event | When it triggers |
|---|---|
| When element is clicked |
| When element is double-clicked |
| When mouse enters element |
| When mouse leaves element |
| When element gets focus (tab or click) |
| When element loses focus |
| When input value changes |
| When user types in input |
| When page finishes loading |
| When image fails to load |
Note on Inline Events:
Inline events are easy for beginners, but professional developers prefer addEventListener() in JavaScript because:
Separates HTML from JavaScript (cleaner code)
Can add multiple events to same element
Easier to debug and maintain
Modern way (addEventListener):
1<button id="myButton">Click Me</button>
2
3<script>
4 document.getElementById('myButton').addEventListener('click', function() {
5 alert('Button clicked!');
6 });
7
8 // Can add multiple events to same button
9 document.getElementById('myButton').addEventListener('mouseover', function() {
10 this.style.backgroundColor = 'yellow';
11 });
12</script>