Open In App

How to get a dialog box if there is no internet connection using jQuery ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to check the internet connection using jQuery. We will be using navigator.onLine which will return true if an internet connection is available otherwise it will return false.

Syntax:

navigator.onLine

Returns:

  • True: If the internet connection is available.
  • False: If the internet connection is not available.

Example 1: This example will check whether the internet connection is available or not and show an alert box on button click.

HTML




<!DOCTYPE html>
<html>
  <head>
    <!--Including JQuery-->
    <script src=
    <script>
      $(document).ready(function () {
        // Function to be called on button click
        $("button").click(function () {
  
          // Detecting the internet connection
          var online = navigator.onLine; 
          if (online) {
  
            // Showing alert when connection is available
            $("#message").show().html("Connected!");
          } else {
  
            // Showing alert when connection is not available
            alert("No connection available");
          }
        });
      });
    </script>
  </head>
  <body>
    <p>
      Click the button below to check 
      your internet connection.
    </p>
  
    <button>Check connection</button>
    <div style="height: 10px"></div>
    <div id="message"></div>
  </body>
</html>


Output:

Check connection

Example 2: This example automatically checks for an internet connection after every 3 seconds. If there is no internet connection it will show an alert.

HTML




<!DOCTYPE html>
<html>
  <head>
    <!--Including JQuery-->
    <script src=
    </script>
    <script>
  
      // Function to check internet connection
      function checkInternetConnection() {
  
        // Detecting the internet connection
        var online = navigator.onLine;
        if (!online) {
  
          // Showing alert when connection is not available
          $("#message").show().html("No connection available");
        }
      }
  
      // Setting interval to 3 seconds
      setInterval(checkInternetConnection, 3000);
    </script>
  </head>
  <body>
    <p>
      It will automatically check for internet
      connection after every 3 seconds.
    </p>
  
    <div style="height: 10px"></div>
    <div id="message"></div>
  </body>
</html>


Output:

No connection available



Last Updated : 18 Apr, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads