The moment you connect to the internet, your status is considered to be online and once you are disconnected, your status is considered to be offline.
The Navigator API contains onLine property and it returns a Boolean value depending upon the state of your connectivity. The online and offline events get fired whenever there is a change in the state of connectivity.
In the following example, depending on the connectivity of the user, we will display offline or online on the screen. Please have a look over the code example and the steps given below.
HTML & CSS
We have 2 elements in the HTML file (div and span). The div element with a class of container is just a wrapper for the span element.
We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
We are getting the initial state of connectivity by using the onLine property and storing it in the status variable. This onLine property returns a Boolean value.
We have 2 methods, online() and offline(). The online() method will change the background color of the div element to green and display the text “Online” in the span element. The offline() method will change the background color of the div element to red and display the text “Offline” in the span element.
If the status is true, that means we are connected to the internet and will execute the online() method.
If the status is false, that means we are not connected to the internet and will execute the offline() method.
We have attached online and offline events listener to the window object. Depending upon the event, it will execute the corresponding method.
const status = window.navigator.onLine;
document.getElementById('container').style.backgroundColor = 'green';
document.querySelector('span').textContent = 'Online';
document.getElementById('container').style.backgroundColor = 'red';
document.querySelector('span').textContent = 'Offline';