onoffline

The onoffline event is triggered when the browser loses its internet connection. It is the inverse of the ononline event.

onoffline event

The onoffline event handler triggers a script when the browser disconnects from the internet. This event is helpful for offering feedback or managing offline states in web applications.

Syntax

In HTML

index.html
<element onoffline="myScript">

In JS

script.js
object.onoffline = myScript;

In JavaScript, the addEventListener() function is used.

script.js
object.addEventListener("offline", myScript);

Example

::event-onoffline ::
index.html
<!DOCTYPE html>
<html>
<h1>HTML DOM Events</h1>
<h2>The onoffline Event</h2>
<body ononline="onFunction()" onoffline="offFunction()">
<p><b>NOTE:</b> There will only be an "output" from this example when the browser shifts from online to offline.</p>
<p id="demo"></p>

<script>
function onFunction() {
  document.getElementById("demo").innerHTML = "Your browser is working online.";
}

function offFunction() {
  document.getElementById("demo").innerHTML = "Your browser is working offline.";
}
</script>

</body>
</html>

Values

Conclusion

The onoffline event is an essential tool for handling scenarios where a browser loses internet connectivity. By triggering scripts when the user goes offline, it allows developers to offer better user feedback, such as notifying the user of a loss of connection. This event is especially useful in web applications that need to respond dynamically to network status changes, providing a seamless experience for users even when offline.