jQuery error() Method

jQuery | error() Method: Learn about the jQuery error() Method with its usages, syntax, and examples.
Submitted by Pratishtha Saxena, on October 27, 2022

error() Method

Events in jQuery are the actions that the user performs on the web page. It can be anything – related to mouse clicks, keyboard presses, etc. Using jQuery, we can control these events in the order we want and can also attach some custom functions to it if needed. That means, we can use predefined event methods for the actions and also define a function that gets fired when the event method is triggered. Overall, this makes the website more dynamic on the user's end. Let's learn about the error() method here.

The error event triggers the error() method in jQuery. This method helps us to address the error encountered by the element. Generally, the error can be when the element is not loaded properly. Once this event is triggered, then an appropriate function can be fired for the element.

error() Method Syntax

$('selector').error();
$('selector').error(function);

A function can be declared that gets fired when the error event gets triggered.

Note: Error event has been deprecated in version 1.8 and then further removed from version 3.0.

The following example shows how the error event triggers the error() method when the provided button is clicked. Further, the error() method gets executed for the image.

jQuery error() Method Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
  </head>
  
  <body>
    <h2>jQuery Event - Error</h2>
    <p>If the image is not loaded properly, then error event is triggered</p>
    <button>Error</button>
    <hr>
    <img style="height: 200px;" id="myImg" src="https://media.istockphoto.com/photos/mountain-landscape-picture-id517188688?k=20&m=517188688&s=612x612&w=0&h=i38qBm2P-6V4vZVEaMy_TaTEaoCMkYhvLCysE7yJQ5Q=">
    <hr>
    <h3></h3>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $('img').error(function(){
            $('h3').html('Image Not Loaded Properly !')
        });
        $('button').click(function(){
            $('img').error();
        });
    });
  </script>
</html>



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.