Show Output
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JavaScript Detect Internet Connection Status</title> <style> body { text-align: center; font-family: "Segoe UI", Arial, sans-serif; } #status { border: 2px solid; padding: 15px 20px 15px 40px; width: 160px; margin: 0 auto; border-radius: 20px; font-size: 30px; font-weight: bold; text-transform: uppercase; position: relative; } #status.online { color: green; } #status.offline { color: red; } #status.online::before, #status.offline::before { width: 25px; height: 25px; content: ""; border-radius: 15px; box-shadow: 0 0 8px; position: absolute; left: 20px; top: 25px; } #status.online::before { background: green; } #status.offline::before { background: red; } </style> </head> <body> <script> var hint = document.getElementById("hint"); // Defining function to update connection status function updateConnectionStatus() { var status = document.getElementById("status"); if(navigator.onLine) { status.innerHTML = "Online"; status.classList.add("online"); status.classList.remove("offline"); } else { status.innerHTML = "Offline"; status.classList.add("offline"); status.classList.remove("online"); } } // Attaching event handler for the load event window.addEventListener("load", updateConnectionStatus); // Attaching event handler for the online event window.addEventListener("online", function(e) { updateConnectionStatus(); hint.innerHTML = "And we're back!"; }); // Attaching event handler for the offline event window.addEventListener("offline", function(e) { updateConnectionStatus(); hint.innerHTML = "Hey, it looks like you're offline."; }); </script> <div id="status"></div> <p>Toggle your internet connection on/off to see how it works.</p> <p id="hint"></p> </body> </html>