Categories
JavaScript JavaScript Basics

JavaScript Events Handlers — onblur and onerror

Spread the love

In JavaScript, events are actions that happen in an app. They are triggered by various things like inputs being entered, forms being submitted, changes in an element like resizing, or errors that happen when an app is running, etc.

We can assign event handlers to respond to these events. Events that happen to DOM elements can be handled by assigning an event handler to properties of the DOM object for the corresponding events.

In this article, we will look the onblur and the onerror property.

window.document.onblur

The onblur property let’s set an event handler function to it to handle the blur event, where the object that represents the element that can lose focus has lost focus. For example, we can attach a onblur event listener function by writing the following code:

document.onblur = () => {  
  console.log('Document lost focus.');  
};

After adding the code above, when we click outside the page then ‘ Document lost focus.’ should be logged.

window.document.onerror

The onerror property lets us attach an event handler to handle situations when the error event is triggered.

The error event is triggered when a JavaScript run time error occurs, such as when syntax errors or exceptions are being thrown within handlers occurs. The error event handler can take a parameter that has the ErrorEvent object in this case.

These errors get bubbled up to the window object by default. It’s also fired when a resource, like an image or script element, fails to load. An error event using the Event interface will be passed into the error event handler in this case. These errors do not get bubbled up to the window object, but it can be handled in window.addEventListener with useCapture is set to true which is the third argument of the addEventListener method.

For historical reasons, the arguments that are passed into window.onerror are different from the ones that are passed into element.onerror as well as on error-type window.addEventListener handlers. window.onerror’s error handler function has the following function signature:

window.onerror = function(message, source, lineno, colno, error) { ... }

Where message is the error message, the source is the string of the URL of the script that threw the error. The lineno parameter is a number that has the line number where the error was raised. The colno parameter is a number that has the column number for the line where the error occurred. The error parameter has the Error object. The Error object has the following standard properties:

  • constructor — the function that created the instance’s prototype
  • message — the error message
  • name — the error name

It also has vendor-specific properties. For Microsoft browsers, the Error object has the following additional properties:

  • description — the error description, which is similar to message
  • number — the error number

For Mozilla browsers, the following additional properties are added to the error object:

  • fileName — the path to the file that raised the error
  • lineNumber — the line number that raised the error
  • columnNumber — the column number of the line that raise the error
  • stack — the stack trace of the error

If an error event handler is passed into the second argument of the window.addEventListener method, then the function signature of the event handler is significantly different. It should have one event parameter which is the ErrorEvent, so the function signature should be the one below:

window.addEventListener('error', function(event) { ... })

The ErrorEvent inherits all the properties from the Event object plus the following properties are included:

  • message — a read-only property that as the string of the human-readable error message which describes the error
  • filename — a read-only string property that has the name of the script of the file in which the error occurred
  • lineno — a read-only integer that has the line number of the script of the file on which the error occurred
  • colno — a read-only integer that has the column number of the script where the error occurred
  • error — a read-only JavaScript object that has the data about the event

If the onerror is a property of anything other than window, then the event handler that we assign to it should have the same signature as we have above, which is only the event parameter which will have the ErrorEvent passed in when an event occurs.

So with the onerror event handler we can handle any error that occurs when loading the page and running the scripts that are loaded on the page. For example, we can use it to handle the situation when an image fails to load by providing an alternative image which we can load.

For example, if we want to load an image that might exist, then we can add an onerror attribute to the img element to load the fallback image like in the following code:

<img src="invalid.gif" onerror="this.src='[https://images.unsplash.com/photo-1556742521-9713bf272865?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1534&q=80'](https://images.unsplash.com/photo-1556742521-9713bf272865?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1534&q=80');" />

To handle errors during script loading, we can write the following code:

<!DOCTYPE html>  
<html>  
  <head>  
    <title>Error</title>  
  </head>  
  <body>  
    <script src="main.js"></script>  
    <script src="error.js"></script>  
  </body>  
</html>

Then in main.js we add our onerror event handler:

window.onerror = (message, source, lineno, colno, error) => {  
  console.log(message);  
  console.log(source);  
  console.log(lineno);  
  console.log(colno);  
  console.log(error.toString());  
};

Then we put some expressions or statements that throws an error in error.js like the following code:

xyz

Then we should get the error logged in our console.log statements inside the onerror event handler in main.js . We should get something like the following output from the console.log statements:

Uncaught ReferenceError: xyz is not defined  
[http://localhost:3000/error.js](http://localhost:3000/error.js)  
1  
1  
ReferenceError: xyz is not defined

The first console.log output has the error message. The second line in the output has the path to the script that caused the error message. Line 3 has the line number of the script where the error occurred. The fourth line has the column number of the line that caused the error, and the last line has the Error object converted to a string, which returns the error message.

If we instead write use the window.addEventListener method to add the event handler, then we can write the following code to log the ErrorEvent object:

window.addEventListener("error", event => {  
  console.log(event);  
});

Then we should get something like the following output from the console.log statement in the event handler above:

bubbles: false  
cancelBubble: false  
cancelable: true  
colno: 1  
composed: false  
currentTarget: Window {parent: Window, postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, …}  
defaultPrevented: false  
error: ReferenceError: xyz is not defined at [http://localhost:3000/error.js:1:1](http://localhost:3000/error.js:1:1)  
eventPhase: 0  
filename: "[http://localhost:3000/error.js](http://localhost:3000/error.js)"  
isTrusted: true  
lineno: 1  
message: "Uncaught ReferenceError: xyz is not defined"  
path: [Window]  
returnValue: true  
srcElement: Window {parent: Window, postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, …}  
target: Window {parent: Window, postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, …}  
timeStamp: 68.510000128299  
type: "error"

In the output above, we get everything from the Event object plus the additional properties from the ErrorEvent object that we listed above like the error property, message property and the filename property.

Conclusion

With the onblur property, we can set an event handler that can handle the blur event. The onerror property lets us set the event handler for when the error event occurs, which happens when something fails to load like an image or a script that fails to run because of some error.

These are handy event handlers that let us handle user interaction and unexpected errors when resource load respectively.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *