How to create an Internet status viewer using JavaScript?

In this tutorial, we are sharing the source code a simple internet status viewer using HTML, CSS and JavaScript. This tool will looks like:

Network connected image
No connection - network connection viewer

As you can see from the image above, the connection status will be visible. If the network is off then the connection status will be "no connection" in red colour ( look  the second image).

I have used font-awesome to display the wifi icon. Also I am connected the project with font-awesome using URL. 

Files and folder

For this project you want to create a folder containing the files called index.html and  style.css. I am added the javascript with the html file. 

index.html


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>connection test</title>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

</head>
<body ononline="myfunction()">
    <div class="network">
        <i class="fa fa-wifi"></i>
        <h3 id="message">No connection</h3>
        
    </div>
</body>
<script>
    let message = document.getElementById("message");
    let wifi = document.querySelector(".fa-wifi");
        let messageOnline = () => {
            message.textContent = "Connected";
            message.style.cssText = "color: #689f38";
            wifi.style.cssText = "color: white; background-color:#689f38;";
        };
        let messageOffline = () => {
            message.textContent = "No Connection";
            message.style.cssText = "color: #d32f2f";
            wifi.style.cssText = "color: red; background-color:white;";
        };
        if (window.navigator.onLine) {
            messageOnline();
        } else {
            messageOffline();
        }
        window.addEventListener("online", messageOnline);
        window.addEventListener("offline", messageOffline);
</script>
</html>

style.css


*{
    margin: 0%;
    padding: 0%;
    box-sizing: border-box;
}
.network{
    display: flex;
    height: 100vh;
    align-items: center;
    justify-content: center;
}
.network i{
    padding: 30px;
    font-size: 35px;
    background-color: rgb(245, 244, 244);
    border-radius: 50%;
    transition: 2s;
    border: 2px solid;
}
.network h3{
    padding-left: 15px;
    color: brown;
    font-size: 25px;
}



Discussions

Post a Comment