JavaScript error events provide information on variety of possible errors, for instance: document not loading, image not loading, error exception in page script, etc...

The onerror() is event handler of JavaScript will be triggered if and when there is an error happening while loading or executing a web page. The even provides following information on the nature of the error:

  • Error message – This is displayed on browser which states the reason of the error.
  • URL – Link of the file in which error occurred.
  • Line Number – Line number in the file which caused the error event to be triggered.

The onerror() event can be added into an HTML and JavaScript code as shown below.

Syntax for onerror() event in HTML code

<element onerror=“myScript()”></element>

The JavaScript "myScript" function will be called when the error event triggers.

Example with a HTML based onerror() event attribute

Syntax for onerror() event in JavaScript code

object.onerror = function(){myScript}; 

Ifthere is an error happened in a page the function "myScript" is triggered.

Example with a onerror() event handled inside a JavaScript code

Syntax for onerror() event in JavaScript code and addEventListener() method

NOTE: The addEventListener() method was not supported in IE8 and earlier versions.

Object.addEventListener(“error”, myScript); 

When an error event occurs it’s handler "myScript" is called.

Example with a onerror() event handled by addEventListener() method


›› go to examples ››