View video tutorial

HTML onoffline Attribute

HTML

The HTML onoffline attribute is an event handler that triggers a script to execute when the browser loses its internet connection.

Definition and Usage


➔ This is the opposite of the ononline attribute.

➔ It is mainly used in the <body> element or Window object.

➔ The primary purpose is to improve the user experience by displaying messages to the user about network connectivity or switching to offline functionality.

Syntax
//In HTML
<body onoffline="myFunction()"></body>

//In JavaScript
window.addEventListener("offline", (event) => {
  alert("You are now offline!");
  // Add code to handle offline state
});

// Or using the event handler property:
window.onoffline = (event) => {
    alert("Connection lost.");
};
function myFunction() {
    alert("You are now offline!");
}

Example
<!DOCTYPE html>
<html>
<head>
    <title>HTML onoffline attribute example</title>
</head>
<body onoffline="myFunction()">
    <h1>HTML onoffline attribute example</h1>
    <p>Try enabling/disabling your network connection to trigger event.</p>
    <script>
        function myFunction() {
            alert("You are now offline!");
        }
    </script>
</body>
</html>

Applies to

This attribute can be used on the following element.

Attribute Element
onoffline <body>