How to detect the network status is online or offline with Javascript?

In this example, we'll know how to detect the network status is online or offline with Javascript.

Step 1: We have a bit of the codes below, add to your code inside the body tag

<div id="status"></div>
<script>
function networkStatusDetect() {
 let status = "<div class='offline'>Offline</div>" ;
 if(navigator.onLine){
  status = "<div class='online'>Online</div>" ;
 }
 document.getElementById("status").innerHTML = status;
}
networkStatusDetect();
</script>
Copy this code

In the codes above, we used the onLine property of the Navigator object returns a Boolean value that specifies whether the browser is in online or offline mode.

Step 2: Add the CSS style codes to create the difference between the offline and online status

#status{
 font-size:20px;
    font-weight:bold;
}
.offline{
 color:red;
}
.online{
 color:green;
}
Copy this code

For change network status, press CTRL + Shift + I on your Chrome browser to open the Developer tools, select Network tab and check or uncheck and refresh the page to see the result

© 2019 4codev

Created with love by Sil.