Detect Internet Connection: HTML, CSS, and JavaScript Guide (Source Code)

Faraz

By Faraz -

Learn how to detect internet connection using HTML, CSS, and JavaScript. Create responsive online/offline indicators for your web app.


Learn how to detect internet connection using HTML, CSS, and JavaScript.jpg

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Preview
  6. Conclusion

Detecting the status of an internet connection is vital for ensuring a smooth user experience when using web applications. By leveraging the power of HTML, CSS, and JavaScript, developers can create a robust solution to inform users about their online status. In this guide, we'll explore how to implement internet connection detection using these technologies, enabling you to provide a seamless browsing experience for your users.

Join My Telegram Channel to Download the Project Source Code: Click Here

Prerequisites:

Before starting this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript. Additionally, you will need a code editor such as Visual Studio Code or Sublime Text to write and save your code.

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will create a div element to hold the online/offline status indicator.

After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.

Let's break down the HTML code step by step:

1. <!DOCTYPE html>: Declares the document type and version of HTML being used.

2. <html lang="en">: Defines the root element of the HTML document with the language attribute set to English.

3. <head>: Contains meta-information about the HTML document, such as character encoding, viewport settings, and title.

  • <meta charset="UTF-8">: Specifies the character encoding for the document as UTF-8, which supports a wide range of characters.
  • <meta http-equiv="X-UA-Compatible" content="IE=edge">: Provides instructions to the browser on how to render the webpage, ensuring compatibility with the latest version of Internet Explorer.
  • <meta name="viewport" content="width=device-width, initial-scale=1.0">: Configures the viewport to adjust the width of the webpage to the device's screen width and sets the initial zoom level to 1.0.
  • <title>Detect Internet Connection</title>: Sets the title of the webpage to "Detect Internet Connection".
  • <link rel='stylesheet' href='https://unicons.../...'>: Links an external CSS stylesheet from the given URL, which contains icon styles.
  • <link rel="stylesheet" href="styles.css">: Links another external CSS stylesheet named "styles.css", which contains custom styles for the webpage.

4. <body>: Contains the content of the webpage that will be displayed to the user.

  • <div class="wrapper">: A wrapper div that contains the main content of the webpage.
  • <div class="toast">: A div element representing a toast notification, often used to display brief messages to the user.
  • <div class="content">: Contains the content of the toast notification.
  • <div class="icon"><i class="uil uil-wifi"></i></div>: Displays an icon representing a Wi-Fi connection using the "uil uil-wifi" class.
  • <div class="details">: Contains the details of the toast notification.
  • <span>You're online now</span>: Displays a brief message indicating that the user is currently online.
  • <p>Hurray! Internet is connected.</p>: Provides additional information confirming that the internet connection is established.
  • <div class="close-icon"><i class="uil uil-times"></i></div>: Displays a close icon using the "uil uil-times" class, allowing the user to dismiss the toast notification.

5. <script src="script.js"></script>: Links an external JavaScript file named "script.js", which contains scripts responsible for detecting internet connection status.

This is the basic structure using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

Once the basic HTML structure of the website is in place, the next step is to add styling to the online/offline indicators using CSS.

Next, we will create our CSS file. In this file, we will style the online/offline indicators to enhance the user experience by providing clear visual cues.

Let's break down the CSS code step by step:

1. @import url('https://fonts.go...');: This line imports the Google Fonts stylesheet for the "Poppins" font family with various weights, which will be used throughout the webpage.

2. *: Select all elements in the document.

  • margin: 0;, padding: 0;: Resets the margin and padding to zero for all elements to ensure consistent spacing.
  • box-sizing: border-box;: Specifies that the width and height of an element should include padding and border, but not the margin.
  • font-family: 'Poppins', sans-serif;: Sets the default font for all elements to "Poppins" and falls back to a generic sans-serif font if "Poppins" is not available.

3. body: Selects the <body> element.

  • overflow: hidden;: Hides any content that overflows the body.
  • background: #f2f2f2;: Sets the background color of the body to a light grayish color.

4. .wrapper: Selects elements with the class "wrapper".

  • position: absolute;: Positions the wrapper element absolutely relative to its closest positioned ancestor.
  • top: 20px;, left: 20px;: Sets the distance of the wrapper from the top and left edges of its containing element to 20 pixels.
  • animation: show_toast 1s ease forwards;: Applies the "show_toast" animation to the wrapper with a duration of 1 second, using the "ease" timing function, and retaining the final state of the animation.

5. @keyframes show_toast: Defines a keyframe animation named "show_toast".

  • Specifies different stages of the animation:
  • From 0% to 40%: Translates the toast element from left to right.
  • From 40% to 80%: Moves the toast slightly back.
  • From 80% to 100%: Restores the toast to its final position.

6. .wrapper.hide: Select elements with the class "hide" within the wrapper.

  • animation: hide_toast 1s ease forwards;: Applies the "hide_toast" animation to hide the toast.

7. @keyframes hide_toast: Defines a keyframe animation named "hide_toast" to hide the toast.

  • Specifies different stages of the animation to hide the toast:
  • From 0% to 40%: Move the toast slightly back.
  • From 40% to 80%: Fades out the toast and disables pointer events.
  • From 80% to 100%: Translates the toast out of the screen.

This will give our indicators an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap');
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}
body{
  overflow: hidden;
  background: #f2f2f2;
}
.wrapper{
  position: absolute;
  top: 20px;
  left: 20px;
  animation: show_toast 1s ease forwards;
}
@keyframes show_toast {
  0%{
    transform: translateX(-100%);
  }
  40%{
    transform: translateX(10%);
  }
  80%, 100%{
    transform: translateX(20px);
  }
}
.wrapper.hide{
  animation: hide_toast 1s ease forwards;
}
@keyframes hide_toast {
  0%{
    transform: translateX(20px);
  }
  40%{
    transform: translateX(10%);
  }
  80%, 100%{
    opacity: 0;
    pointer-events: none;
    transform: translateX(-100%);
  }
}
.wrapper .toast{
  background: #fff;
  padding: 20px 15px 20px 20px;
  border-radius: 10px;
  border-left: 5px solid #2ecc71;
  box-shadow: 1px 7px 14px -5px rgba(0,0,0,0.15);
  width: 430px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.wrapper .toast.offline{
  border-color: #ccc;
}
.toast .content{
  display: flex;
  align-items: center;
}
.content .icon{
  font-size: 25px;
  color: #fff;
  height: 50px;
  width: 50px;
  text-align: center;
  line-height: 50px;
  border-radius: 50%;
  background: #2ecc71;
}
.toast.offline .content .icon{
  background: #ccc;
}
.content .details{
  margin-left: 15px;
}
.details span{
  font-size: 20px;
  font-weight: 500;
}
.details p{
  color: #878787;
}
.toast .close-icon{
  color: #878787;
  font-size: 23px;
  cursor: pointer;
  height: 40px;
  width: 40px;
  text-align: center;
  line-height: 40px;
  border-radius: 50%;
  background: #f2f2f2;
  transition: all 0.3s ease;
}
.close-icon:hover{
  background: #efefef;
} 

Step 3 (JavaScript Code):

Finally, we need to create a function in JavaScript to detect internet connectivity.

Let's break down the JavaScript code step by step:

1. Variable Declarations:

  • wrapper, toast, title, subTitle, wifiIcon, closeIcon: These variables store references to various elements of the toast notification system obtained using the querySelector method.

2. Window onload Event Handler: This code block executes once the window and its contents have finished loading.

3. ajax Function: This function performs an AJAX request to a specified URL to check the internet connection status.

  • It creates a new XMLHttpRequest object.
  • Opens a GET request to the specified URL.
  • Handles the response to the AJAX request:
  • If the status is between 200 and 300, it indicates a successful request, and the user is considered online. The toast notification is updated to indicate an online status.
  • If there's an error or the status code is not in the success range, it calls the offline function to handle the offline status.
  • It sets an error handler to catch any errors that might occur during the AJAX request.
  • Finally, it sends the AJAX request.

4. offline Function: This function is called when the user is determined to be offline.

  • It updates the toast notification to indicate an offline status.
  • It modifies the content of the toast to display an appropriate message for offline status.

5. Interval: This setInterval function calls the ajax function every 100 milliseconds to continuously check the internet connection status.

Create a JavaScript file with the name script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

const wrapper = document.querySelector(".wrapper"),
toast = wrapper.querySelector(".toast"),
title = toast.querySelector("span"),
subTitle = toast.querySelector("p"),
wifiIcon = toast.querySelector(".icon"),
closeIcon = toast.querySelector(".close-icon");

window.onload = ()=>{
    function ajax(){
        let xhr = new XMLHttpRequest(); //creating new XML object
        xhr.open("GET", "https://jsonplaceholder.typicode.com/posts", true); //sending get request on this URL
        xhr.onload = ()=>{ //once ajax loaded
            //if ajax status is equal to 200 or less than 300 that mean user is getting data from that provided url
            //or his/her response status is 200 that means he/she is online
            if(xhr.status == 200 && xhr.status < 300){
                toast.classList.remove("offline");
                title.innerText = "You're online now";
                subTitle.innerText = "Hurray! Internet is connected.";
                wifiIcon.innerHTML = '<i class="uil uil-wifi"></i>';
                closeIcon.onclick = ()=>{ //hide toast notification on close icon click
                    wrapper.classList.add("hide");
                }
                setTimeout(()=>{ //hide the toast notification automatically after 5 seconds
                    wrapper.classList.add("hide");
                }, 5000);
            }else{
                offline(); //calling offline function if ajax status is not equal to 200 or not less that 300
            }
        }
        xhr.onerror = ()=>{
            offline(); ////calling offline function if the passed url is not correct or returning 404 or other error
        }
        xhr.send(); //sending get request to the passed url
    }

    function offline(){ //function for offline
        wrapper.classList.remove("hide");
        toast.classList.add("offline");
        title.innerText = "You're offline now";
        subTitle.innerText = "Opps! Internet is disconnected.";
        wifiIcon.innerHTML = '<i class="uil uil-wifi-slash"></i>';
    }

    setInterval(()=>{ //this setInterval function call ajax frequently after 100ms
        ajax();
    }, 100);
}

Final Output:

Learn how to detect internet connection using HTML, CSS, and JavaScript.gif

Conclusion:

In conclusion, implementing internet connection detection using HTML, CSS, and JavaScript is crucial for enhancing the usability and reliability of web applications. By following the steps outlined in this guide, you can create responsive online/offline indicators that keep users informed about their connectivity status. Remember to test your implementation across different browsers and network conditions to ensure a consistent experience for all users. With these techniques, you can improve the user experience and minimize frustration caused by unexpected internet disruptions.

Code by: Muhammad Fadzrin Madu

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post