🚀 Detecting If a User is Online/Offline with JavaScript
Tags: javascript, webdev, beginners, tutorial
Published: 2020-06-25 10:39:23

---
title: 🚀 Detecting If a User is Online/Offline with JavaScript 
published: true
description: Easily detect if a user is online or offline with JavaScript.
tags: javascript, webdev, beginners, tutorial
cover_image: https://imgur.com/OyxdfQT.png
---

As developers, we sometimes get used to our great broadband in our offices and localhost being the fastest site ever with no network issues.

In fact, what a lot of people forget is just over half of all internet traffic is driven over mobile phones and unless you are in a booming city, a consistent internet connection is not all that normal. 

This is the first episode in a series which I am going to go over some tips and tricks to easily create a better experience for people who have a bad internet connection. Which if you are building consumer-facing applications could be a huge portion of your users.

In this post, we are going to look at a super-easy way to check if the user is connected to the internet and detect if they lose connection or reconnect so that you can update your UI appropriately depending on the internet status. 

![Online and offline banner](https://imgur.com/gMzf5HJ.png)

---

You can watch my video explanation (where I go into more detail) here or scroll on to keep reading. 💜

{% youtube uuhmkrjeaUE%}

---

By the end of this post, you will have cards that change based on if the user has internet.

### First a little bit of boilerplate

index.html
```html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Network Checker</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="app">
      <h1 class="status">Hello</h1>
    </div>
    <script src="app.js"></script>
  </body>
</html>
```

style.css
```css
body {
  background-color: #555;
}

.app {
  height: 100vh;
  width: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
    Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}

.status {
  padding: 40px;
  min-width: 120px;
  border-radius: 20px;
  background-color: #eee;
  text-align: center;
  font-size: 80px;
}

.status.online {
  border: 8px solid #41a700;
  color: #41a700;
}

.status.offline {
  border: 8px solid #f15c4f;
  color: #f15c4f;
}
```
Add an empty `app.js` file and that's where we will be doing all of the work.

So your folder should look like this:
```
├── app
│   ├── index.html
│   └── style.css
│   └── app.js

```

Let's first create a function to manipulate the DOM based on if the user has connectivity. We will pass it a `boolean` value.

```app.js
  
function hasNetwork(online) {
  const element = document.querySelector(".status");
  // Update the DOM to reflect the current status
  if (online) {
    element.classList.remove("offline");
    element.classList.add("online");
    element.innerText = "Online";
  } else {
    element.classList.remove("online");
    element.classList.add("offline");
    element.innerText = "Offline";
  }
}

```
Next is the fun part.

We will first use `navigator.online` to check if the user has internet when the page initially loads. The `navigator.online` has supported all the way back to IE9 and returns a `boolean` value. 

It is important to remember that browsers implement this feature differently and for more detailed information view the MDN docs [here](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine#Example).

>In Chrome and Safari, if the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return true. So while you can assume that the browser is offline when it returns a false value, you cannot assume that a true value necessarily means that the browser can access the internet.

```js
// Listen for the page to be finished loading
window.addEventListener("load", () => {
  hasNetwork(navigator.onLine);
});
```
### Note 📝
This can at first seem like a pointless step but with the current state of web development tools and best practices, you will find often users have web pages cached and will still be able to access your site offline. So this initial check can be great if they boot up your app and can be made aware their content may be out of date. 



The next thing we will do is add the event listeners for the online and offline events so that we can check when the users' network status changes.

There are two events we care about and that's `online` and `offline`. As I'm sure you can guess, these are triggered when a user switches between offline and online.

```js
window.addEventListener("load", () => {
  hasNetwork(navigator.onLine);

  window.addEventListener("online", () => {
    // Set hasNetwork to online when they change to online.
    hasNetwork(true);
  });

  window.addEventListener("offline", () => {
    // Set hasNetwork to offline when they change to offline.
    hasNetwork(false);
  });
});
```

Now when we go into our app we will get live feedback when the user changes their network status.

![Showing what the status changing would look like](https://media.giphy.com/media/TjGB23m5fidn8e1Opy/giphy.gif)

### So when to use this? 
Maybe you need to tell a user they can't upload a file because they are offline, the live data they are seeing may no longer be up to date because they are offline or anything really. There's dozens of reason you may need to detect the network status and as web developers let's try to make the web a more user-friendly experience for everyone.

I hope this tip helped and until the next one, happy coding! 💜

---

[Follow me on Twitter](https://twitter.com/nialljoemaher)

Subscribe on [Codú Community](https://www.youtube.com/c/Cod%C3%BACommunity)