Introduction to JQUERY - Trapping Errors Using the error() method

Guest Posts Paolo Nikko Nuñal

For those of you who already have programmed in JAVA before, or tried any type of programming language that involves error handling, then you might already know some tricks on your sleeve on dealing with errors. In the case of Java, there is this called "try catch" block that handles with errors. In JQUERY, we also have a method that tries to handle error events in the form of the error() method.

Syntax:

$(selector).error()

$(selector).error([HANDLER([EVENT OBJECT]));


HANDLER(EVENT OBJECT) - function to execute each time the event is called.

Code


<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
        $(document).ready(function(){
            $("#img1").error(function(){
                  alert("Image cannot be loaded");
            });
        });
</script>
</head>
<body>
<img id="img1" src="butterflies.png" alt="image of butterflies" width="300" height="250"><br>
<button type="button" id="btn-load">Load Image</button>
</body>
</html>


Base on our example above, the error() method automatically triggers since it failed to locate the "butterflies.png" file. An alert message is displayed indicating that the file doe not exist. Most of the time you can use this as a sort of trapping, or to let users know that there are certain elements that cannot be loaded. This will give your site visitors a good use experience since it will track HTML elements that have errors. You can also use this on loading text or html files using html() or load() methods in JQUERY where it will fail to locate these files.