How to Check Whether User Online/Offline in Javascript

This is a very small and basic tutorial about usage of navigator api to check if user is online or offline.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    
    <div id="container">
        <span></span>
    </div>

    <script src="script.js"></script>
</body>
</html>
const status = window.navigator.onLine;
if(status) online()
else offline()


window.addEventListener('online', online);
window.addEventListener('offline', offline);


function online(){
    document.getElementById('container').style.backgroundColor = 'green';
    document.querySelector('span').textContent = 'Online';
}

function offline(){
    document.getElementById('container').style.backgroundColor = 'red';
    document.querySelector('span').textContent = 'Offline';
}
#container {
    width: 100%;
    border: 1px solid black;
    text-align: center;
    color: #fff;
}
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •