jQuery error() Method |
-- Learning not just technology, but also dreams!
jQuery error() Method
The error() method attaches an event handler to the "error" event of the selected elements.
This method is commonly used to handle errors in image loading or other resources.
Syntax
$(selector).error(function)
Parameter Description
- function: A function to be executed when the error event occurs.
Example
Below is an example demonstrating how to use the error() method to detect image loading failures:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("img").error(function(){
alert("Image failed to load!");
});
});
</script>
</head>
<body>
<img src="invalid-image.jpg" alt="This image does not exist">
</body>
</html>
When the browser tries to load an image that doesn't exist (e.g., a broken link), the error() function will trigger and display an alert message.
Notes
- The
error()method is primarily used for handling image loading errors. - It can also be applied to other types of resources such as scripts, stylesheets, etc., although it's less common.
- For modern browsers, consider using the
onerrorattribute directly on HTML elements for better control and performance.
YouTip