In today’s world, the internet is essential for many websites and applications to function properly. To provide a seamless experience for users, it’s important to check the internet connection and take the necessary actions.
In this blog post, we’ll show you how to check internet connection and display relevant notifications using HTML, CSS, and JavaScript. Whether you’re new to web development or an experienced developer, you’re sure to learn something new about detecting network status with plain JavaScript.
In this project, when the user’s device goes offline, there will be a displayed offline notification with a 10-second timer to reconnect. There will also be a “Reconnect Now” button that allows users to try reconnecting to the internet immediately. Once the user’s device is back online, the notification will change to “Restored Connection.”
Video Tutorial of Check Network Status in JavaScript
If you’re excited to see this project in action, you can click here to view a live demo of it. Additionally, if you prefer visual learning, you can watch a given YouTube video that shows how to check an internet connection using HTML, CSS, and JavaScript. Alternatively, you can continue reading this post for a written guide on the same topic.
Steps to Check Internet Connection in JavaScript
We’ll check the Internet connection and display the relevant notification using HTML, CSS, and JavaScript in 3 simple steps.
1. Setting up the project
In the initial step, we will create a new directory for our project. You can name it whatever you want, and inside this directory, 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.
2. Creating the notification
In the second step, we will create the layout and style the notification using HTML and CSS. Then, we will use JavaScript to check the device’s internet connection status.
In your 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.
<!DOCTYPE html> <!-- Coding By CodingNepal - youtube.com/codingnepal --> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Check Internet Connection | CodingNepal</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>
In your style.css
file, add the following CSS code to style the notification: If you want, you can change the font, size, color, and background of the notification by slightly modifying this code.
/* 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; } }
Keep in mind that the notification won’t show on the page because we’ve added some styles to hide it, which will be controlled by JavaScript.
3. 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:
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);
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.
If you want to understand the specific functionality of a certain script code, you can read the comments on each line to gain more insight.
Conclusion and Final Words
By following the steps in this blog post, you’ve learned how to use HTML, CSS, and JavaScript to check the internet connection and display appropriate notifications to the user. However, keep in mind that there are alternative methods to check an internet connection, such as the JavaScript navigator.onLine method.
But 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. So, a better approach would be to send a request for data to an API that you already know about.
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 by clicking on the given download button. It’s free, and a zip file will be downloaded that contains the project folder with source code files.