How to check internet connection and display notify in JavaScript

How to check internet connection & display notification in HTML CSS And JavaScript

Welcome to Bijan's Blog! Today, we will be discussing how to check internet connection and display relevant notifications using HTML, CSS, and JavaScript. This is an essential task for many websites and applications to function properly and provide a seamless experience for users. Whether you're new to web development or an experienced developer, this tutorial will help you learn how to detect network status with plain JavaScript.

You might know:

How to check internet connection & display notification in HTML CSS And JavaScript

We will be using a three-step process to check internet connection and display notifications:

Setting up the project: Create a new directory for the project and within it, create three files: index.html, style.css, and script.js. These files will contain the necessary HTML, CSS, and JavaScript code for checking the internet connection status.


<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="utf-8">
  <title>Check Internet Connection </title>
  <link rel="stylesheet" href="style.css">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://unicons.iconscout.com/release/v3.0.6/css/line.css">
  <script src="script.js" defer></script>
</head>
<body>
  <div class="popup">
    <div class="icon">
      <i class=""></i>
    </div>
    <div class="details">
      <h2 class="title"></h2>
      <p class="desc"></p>
      <button class="reconnect">Reconnect Now</button>
    </div>
  </div>
</body>
</html>

Creating the notification: Use HTML and CSS to create the layout and style of the notification. Then, use JavaScript to check the device's internet connection status. In the index.html file, add the following HTML code to create the basic structure of the notification. The title, description, and icon name for this notification will be inserted by the JavaScript code. In the style.css file, add the following CSS code to style the notification. You can change the font, size, color, and background of the notification by slightly modifying this code. Note that the notification won't show on the page initially as we've added some styles to hide it, which will be controlled by JavaScript.


/* Import Google font - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap');
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  background: #E3F2FD;
}
.popup {
  position: absolute;
  left: 50%;
  top: -25%;
  visibility: hidden;
  width: 490px;
  border-radius: 5px;
  padding: 13px 17px 20px;
  background: #fff;
  display: flex;
  border-top: 3px solid #EA4D67;
  transform: translateX(-50%);
  box-shadow: 0 10px 25px rgba(52,87,220,0.1);
  transition: all 0.25s ease;
}
.popup.show {
  top: 0;
  visibility: visible;
}
.popup.online {
  border-color: #2ECC71;
}
.popup .icon i {
  width: 40px;
  height: 40px;
  display: flex;
  color: #fff;
  margin-right: 15px;
  font-size: 1.2rem;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: #EA4D67;
}
.popup.online .icon i {
  background: #2ECC71;
}
.popup .title {
  font-size: 1.2rem;
}
.popup .desc {
  color: #474747;
  margin: 3px 0 10px;
  font-size: 1.04rem;
}
.popup .reconnect {
  border: none;
  outline: none;
  color: #fff;
  cursor: pointer;
  font-weight: 500;
  font-size: 0.95rem;
  padding: 8px 13px;
  border-radius: 4px;
  background: #5372F0;
}
.popup.online .reconnect {
  background: #bfbfbf;
  pointer-events: none;
}

@media screen and (max-width: 550px) {
  .popup {
    width: 100%;
    padding: 10px 15px 17px;
  }
}

Checking the internet connection: In the final step, we will add the functionality to check the internet connection and display the relevant notification accordingly. To do this, add the following JavaScript code to your script.js file. In the code, you can see that to check if the device has an internet connection or not, we send requests for data to an API every 3 seconds and check if they are successful. If the requests fail, it indicates that the device is offline, and we will display the notification with a 10-second timer to wait before rechecking the connection.


const popup = document.querySelector(".popup"),
wifiIcon = document.querySelector(".icon i"),
popupTitle = document.querySelector(".popup .title"),
popupDesc = document.querySelector(".desc"),
reconnectBtn = document.querySelector(".reconnect");

let isOnline = true, intervalId, timer = 10;

const checkConnection = async () => {
    try {
        // Try to fetch random data from the API. If the status code is between 
        // 200 and 300, the network connection is considered online 
        const response = await fetch("https://jsonplaceholder.typicode.com/posts");
        isOnline = response.status >= 200 && response.status < 300;
    } catch (error) {
        isOnline = false; // If there is an error, the connection is considered offline
    }
    timer = 10;
    clearInterval(intervalId);
    handlePopup(isOnline);
}

const handlePopup = (status) => {
    if(status) { // If the status is true (online), update icon, title, and description accordingly
        wifiIcon.className = "uil uil-wifi";
        popupTitle.innerText = "Restored Connection";
        popupDesc.innerHTML = "Your device is now successfully connected to the internet.";
        popup.classList.add("online");
        return setTimeout(() => popup.classList.remove("show"), 2000);
    }
    // If the status is false (offline), update the icon, title, and description accordingly
    wifiIcon.className = "uil uil-wifi-slash";
    popupTitle.innerText = "Lost Connection";
    popupDesc.innerHTML = "Your network is unavailable. We will attempt to reconnect you in <b>10</b> seconds.";
    popup.className = "popup show";

    intervalId = setInterval(() => { // Set an interval to decrease the timer by 1 every second
        timer--;
        if(timer === 0) checkConnection(); // If the timer reaches 0, check the connection again
        popup.querySelector(".desc b").innerText = timer;
    }, 1000);
}

// Only if isOnline is true, check the connection status every 3 seconds
setInterval(() => isOnline && checkConnection(), 3000);
reconnectBtn.addEventListener("click", checkConnection);

It's important to note that there are alternative methods to check an internet connection, such as the JavaScript navigator.onLine method. However, the navigator.onLine method is not always reliable as it only checks if a device has a connection to a network, not if the network can actually access the internet. A better approach would be to send a request for data to an API that you already know about.


In conclusion, by following the steps in this tutorial, you've learned how to use HTML, CSS, and JavaScript to check the internet connection and display appropriate notifications to the user. If you encounter any problems or your code is not working as expected, you can download the source code files of this Internet checker project for free by clicking on the given download button. A zip file will be downloaded that contains the project folder with source code files.



Post a Comment

Previous Post Next Post

Contact Form