Search code examples
javascriptjquerygoogle-chromeinternet-connection

Jquery - Check Internet Connection


I want to create jquery listener to check internet connectivity.

    function checkInternetConnection()
    {
        onConnectionClosed:function(){
            dialog.show("Connection closed please wait");
        }
        onConnectionOpened:function(){
            dialog.hide();
        }
    }
    
    $(document).ready(function(){
        checkInternetConnection();
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

So, when the connection is turned off, I want to show a dialog to user. When the connection is back I want to hide the dialog. How can I do this?


Solution

  • this is a snippet from MDN:

    https://developer.mozilla.org/en-US/docs/Online_and_offline_events

    window.addEventListener('load', function() {
    
      function updateOnlineStatus(event) {
        var condition = navigator.onLine ? "online" : "offline";
    
        alert(`you are ${condition}`)
    
      }
    
      window.addEventListener('online',  updateOnlineStatus);
      window.addEventListener('offline', updateOnlineStatus);
    });