Check Internet Connection in HTML 5 using JavaScript

Check Internet Connection in HTML 5 using JavaScript 

 
This blog helps you to determine the internet connectivity for your web application and detects whether you are online or offline using JavaScript.
 
It helps the developer to know about user status and if they are offline would be perform some proper message.
 
You can use many approaches to achieve this task, but I will show the best of HTML5.
 
In the HTML5 there is an event that prompts you the internet status. This is the simplest approach,
 

navigator.onLine

 
This is very simple to get the status of the internet. It returns a Boolean value, true for online and false for offline.
 
Note  The drawback is not supported in all browsers and different Browsers implement this property differently. However, it is not a full-proof solution and may not accurate in all conditions.
 
You can also use another way to to check if the user has the internet connection or not, by register the events on window.onOnline and window.onOffline
 
Example:
  1. <!doctype html><html><head><script>  
  2.         function CheckOnlineStatus(msg) {  
  3.             var status = document.getElementById("status");  
  4.             var condition = navigator.onLine ? "ONLINE" : "OFFLINE";             
  5.             var state = document.getElementById("state");  
  6.             state.innerHTML = condition;             
  7.         }  
  8.         function Pageloaded() {  
  9.             CheckOnlineStatus("load");  
  10.             document.body.addEventListener("offline"function () {  
  11.                 CheckOnlineStatus("offline")  
  12.             }, false);  
  13.             document.body.addEventListener("online"function () {  
  14.                CheckOnlineStatus("online")  
  15.             }, false);  
  16.         }  
  17.     </script><style>  
  18.         ...</style></head><body onload="Pageloaded()"><div id="status"><p id="state"></p></div></body></html>