How to use addEventListener() method In Javascript
This approach involves attaching an event listener to the target element using addEventListener() method.
Syntax:
document.getElementById('image').addEventListener('error', handleError);
Example: The below code explains the use of addEventListener() method to attach the onerror() event.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>
The onerror() Method Example
</title>
</head>
<body style="text-align: center;">
<h2>
Click the below button to remove
the src of image <br> and trigger the
onerror() event method.
</h2>
<img src=
"https://media.w3wiki.org/wp-content/uploads/20240401152503/javascript.jpg">
<br><br>
<button>
Remove Image src
</button>
<script>
const image = document.querySelector('img');
const btn = document.querySelector('button');
image.addEventListener('error', handleError);
btn.addEventListener('click', removeSrc);
function removeSrc(){
image.setAttribute('src', "");
}
function handleError() {
alert('Error loading image!');
}
</script>
</body>
</html>
Output:
What is onerror() Method in JavaScript?
The onerror() method in JavaScript is an event for error handling that occurs during the execution of code. It provides the mechanism to capture and handle runtime errors ensuring graceful error handling and debugging in the web applications.
You can implement the onerror() method using the below methods:
Table of Content
- Using Inline Event Handler
- Using addEventListener() method
Contact Us