Javascript DOM- Events
Execute the code when a user clicks on an HTML element and adds JavaScript code to an HTML event attribute.
onclick=JavaScript
Examples of HTML events:
- When a user clicks the mouse.
- When a web page has loaded.
- When an image has been loaded.
- When the mouse moves over an element.
- When an input field is changed.
- When an HTML form is submitted.
- When a user strokes a key.
Example:
The text of the h1 element is changed when a user clicks on it.
<!DOCTYPE html> <html> <body> <h1 onclick="this.innerHTML='Good!'">welcome to i2tutorials!</h1> </body> </html>
OUTPUT:
GOOD!
HTML Event Attributes:
Assign an onclick event to a button element.
Example:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the date.</p>
<button onclick="displayDate()">The time is?</button>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
<p id="demo"></p>
</body>
</html>
OUTPUT:

onmouseover and onmouseout Events:
These events can be used to trigger a function when the user mouses over, or out of, an HTML element.
Example:
<!DOCTYPE html>
<html>
<body>
<div onmouseover="mOver(this)" onmouseout="mOut(this)"
style="background-color:yellow;width:120px;height:20px;padding:40px;">
Mouse Over Me</div>
<script>
function mOver(obj) {
obj.innerHTML = "Thank You"
}
function mOut(obj) {
obj.innerHTML = "Mouse Over Me"
}
</script>
</body>
</html>
OUTPUT: