The error event represents information about event which are related to errors in scripts or in files. The error event occurs when there is an error in loading or unloading elements. It binds an event handler to “error” event. For example, when you are loading an image, if you missed writing the correct name of image or if you didn’t write the source path correctly, then error event will trigger and display an error message.
The error event is sent to elements which is referenced by document and not loaded correctly by browser. If element was not loaded correctly then the error event is called. It triggers the error event or attaches function when an error event occurs. The event handler for the error event must be attached prior to the browser firing of the error event.
JQuery Error() Syntax
The error event has parameter called function which is optional parameter which defines function to run when event occurs or function executes when the event is triggered.
JQuery Error() Example
- $(“img”).load(function()) line loads the specified image. It attaches event handler to the load event.
- $(“img”).error(function()) line triggers the error event when an element encounters an error.
- <span id=”myimage”> used to group inline elements in the document. It is useful when we are using style sheets to assign set of representational attributes.
- As shown above, in image tag we are setting source path of image. If you mention correct name of the image or path, it will display “Image loaded successfully” or else it will display “Error in loading image” by referring span id “myimage”.
- We are using CSS styles for text to be displayed and these styles are specified in span which determines how the text should be display in the browser.
When you run the above example, you would get the following output :