How to Check Internet Connection in HTML, CSS and JavaScript

Hi to all in this article I am going to tell you all about how to know whether internet connection is online or offline.

How to Check Internet Connection

So, read this article till end and follow the process and add this to your website, so that you website visitors will know when there internet connection becomes offline then they will see a popup message regarding internet connection offline.


Mainly now a days internet becomes most important to run websites and apps to work properly and to provide visitors a smooth experience, it's important to check the internet connection and take the necessary actions.


Here I will tell you in detail about how to check internet connection and display relevant notification by using HTML, CSS and JavaScript. 


You may be new to web development or you are an experienced developer, you are sure to learn something new about detecting the network status with the plain JavaScript.


When the users device becomes offline then there offline notification will be displayed with a ten seconds timer to reconnect and also you can see a reconnect button which allows users to try re connecting to the internet immediately and once internet restored then the notification will change to restored Connection.



Steps to Check Internet Connections

Here we go with three main steps and you should the below three steps to checl internet connection


Creating Project

First of all you need to create a new directory and you can name it as Check_Internet_Connection or add what ever you wished.

In the directory you need to create three files i.e. index.html, style.css and script.js and these files will carry HTML, CSS and JavaScript codes to check the internet connection.



Creating the Warning Notification

Here in this step we first create style and layout of the internet connection checking notification by using HTML and CSS then after we will go for JavaScript to check the connection status.


Now first of all you need to open index.html file and add the following code to create a basic layout of the notification



<!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">
    <!-- Font Awesome CDN link for icons -->
    <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="notification">
      <div class="content">
        <div class="wifi-icon"><i class=""></i></div>
        <div class="details">
          <h2 class="title"></h2>
          <p class="desc"></p>
          <button class="reconnect-btn">Reconnect Now</button>
        </div>
      </div>
    </div>

  </body>
</html>


Now you need to open style.css file and add the following code to style the notification and if you want to change the colors, size, font then you can modify the CSS code.



/* Import Google font - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:[email protected];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;
  }
}


Note: Keep in mind that the notification will not visible on the page because we have added few styles to hide it, which will be controlled by the JavaScript.



Checking Internet Connection

This is the final step for the internet connection checking and displaying the relevant notification to the website user accordingly.

So, to do this you need to open script.js file and add the following code inside it.



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);



So, after adding the three codes in their respective files, now you need to open index.html file in the browser and now you can turn off your internet connection and check whether the code is working correctly or not and if any error occurs then check the paste the code or replace the code again in the files accordingly.



Conclusion

I hope that you all have understood about checking the internet connection by using HTML, CSS and JavaScript easily without any error.

If you encountered with any error or issue, please contact us we will solve that issue as early as possible.



Next Post Previous Post

Cookies Consent

This website uses cookies to analyze traffic and offer you a better Browsing Experience. By using our website.

Learn More