jQuery Event error() Method



The jQuery event error() method is used to handle (manage) error events for selected elements, generally triggered when an element, such as an image or script, fails to load correctly.

The jQuery error() method was deprecated in version 1.8 and removed in version 3.0.

Syntax

Following is the syntax of the jQuery event error() method −

$(selector).error(function)

Parameters

This method accepts an optional parameter as 'function', which is described below −

  • function − A specific function to execute when an error event occurs.

Return Value

This method does not return any value but handles error events on selected elements.

Example 1

Handling image loading errors

The following program demonstrates the usage of the jQuery event error() method −

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<body>
    <img src="logo.png" alt="Tutorialspoint logo">
<script>
    $("img").error(function(){
        alert("Image can't be loaded, Error....!");
    });
</script>
</body>
</html>

Output

After executing the above program, it will display an image −


If the image source file is missing or the image fails to load correctly, a pop-up alert will be displayed on your browser screen −


Example 2

Replacing failed images

The following is another example of using the jQuery error() method. Here, we use this method to handle the error event on the element. If the image fails to load, we replace it with another image −

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<body>
    <img src="logo.png" alt="Tutorialspoint">
<script>
    $("img").error(function(){
        $(this).replaceWith(" <p>Error loading image</p> <img src='error.png'>");
    });
</script>
</body>
</html>

Output

Once the above program is executed, it will display an image −


If the image source file is missing or fails to upload, it will be replaced with the following image −


jquery_ref_events.htm
Advertisements