HTML Inline Events

HTML Inline Events are event handlers written directly inside HTML tags using attributes like onclick, onchange, onmouseover, etc. They allow JavaScript to run when a user interacts with an element. Although easy to use, they are not recommended for large projects because they mix HTML and JavaScript.

3 views
5 min read
Try It Yourself

Experiment with the code in an interactive editor

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

onclick

When element is clicked

ondblclick

When element is double-clicked

onmouseover

When mouse enters element

onmouseout

When mouse leaves element

onfocus

When element gets focus (tab or click)

onblur

When element loses focus

onchange

When input value changes

oninput

When user types in input

onload

When page finishes loading

onerror

When image fails to load

Note on Inline Events:

Inline events are easy for beginners, but professional developers prefer addEventListener() in JavaScript because:

  1. Separates HTML from JavaScript (cleaner code)

  2. Can add multiple events to same element

  3. 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>