• We just launched and are currently in beta. Join us as we build and grow the community.

Ensuring Connectivity: A Guide on Checking Internet Connection with JavaScript

Uktss

Funny Bone Specialist
U Rep
0
0
0
Rep
0
U Vouches
0
0
0
Vouches
0
Posts
151
Likes
181
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 300 XP
This tutorial delves into techniques for verifying internet connectivity in a web application using JavaScript. Its purpose is to offer students and beginners a valuable reference to enhance their knowledge and skills in developing web applications with JavaScript. Throughout this tutorial, I'll be presenting code snippets to illustrate our objectives on this website.

Why is it crucial to guarantee Internet Connection in Web Applications?

Securing a consistent internet connection in web applications is vital for various reasons, particularly in sustaining seamless functionality, delivering real-time updates, and ensuring a responsive user experience. A dependable internet connection becomes essential for applications that heavily rely on continuous data exchange with servers, ensuring users can access and interact with the application without interruptions.

JavaScript offers various valuable built-in event listeners, including the click and input event listeners. Several of these event listeners prove exceptionally useful in achieving the objective of ensuring internet connection in our tutorial. To implement this in our web application, we can introduce a feature that notifies end-users about their internet connection status, leveraging the `offline

` and `online

` event listeners.

In JavaScript, the Offline and Online Event Listeners serve as mechanisms enabling developers to detect changes in the network connectivity status of a web application or device. These events empower developers to dynamically respond to the online or offline state. The `online

` event triggers when the device or browser establishes an internet connection, while the `offline

` event triggers when the device or browser loses internet connection.

To gain a deeper understanding of utilizing the `online

` and `offline

` event listeners, let's construct a simple web application featuring notifications for when the device or browser loses and regains internet connection.

Below is the source code script for the simple web application:

CSS

Generate a new CSS file and copy/paste the following CSS script. This file encapsulates the code for customizing the design of various elements of the application. Save the file as `style.css

`.

  1. @import

    url

    (

    'https://fonts.googleapis.com/css2?f...00;0,700;1,300;1,400;1,500;1,700&display=swap'

    )

    ;
  2. *

    {
  3. font-family

    :

    'Ubuntu'

    ,

    sans-serif

    ;
  4. }

  5. html,

    body{
  6. background-color

    :

    #0093E9

    ;
  7. background-image

    :

    linear-gradient(

    160deg

    ,

    #0093E9

    0%

    ,

    #80D0C7

    100%

    )

    ;
  8. height

    :

    100%

    ;
  9. max-height

    :

    100%

    ;
  10. width

    :

    100%

    ;
  11. max-width

    :

    100%

    ;
  12. overflow

    :

    auto

    ;
  13. margin

    :

    unset;
  14. }
  15. body{
  16. display

    :

    flex;
  17. flex-flow

    :

    column wrap;
  18. align-items

    :

    center

    ;
  19. justify-content

    :

    center

    ;
  20. }

  21. #main-wrapper

    {
  22. width

    :

    100%

    ;
  23. max-width

    :

    500px

    ;
  24. padding

    :

    .75rem

    .75rem

    ;
  25. }

  26. #page-title

    {
  27. font-size

    :

    1.9rem

    ;
  28. font-weight

    :

    bold

    ;
  29. color

    :

    #fff

    ;
  30. text-shadow

    :

    0px

    3px

    5px

    #00000065

    ;
  31. text-align

    :

    center

    ;
  32. }

  33. .flash-message{
  34. position

    :

    fixed

    ;
  35. top

    :

    10px

    ;
  36. right

    :

    10px

    ;
  37. width

    :

    100%

    ;
  38. max-width

    :

    380px

    ;
  39. background-color

    :

    #fff

    ;
  40. box-shadow

    :

    0px

    3px

    7px

    #00000077

    ;
  41. padding

    :

    .35em

    .35em

    ;
  42. z-index

    :

    999

    ;
  43. display

    :

    flex;
  44. flex-flow

    :

    row wrap;
  45. align-items

    :

    center

    ;
  46. justify-content

    :

    center

    ;
  47. border-left

    :

    5px

    solid

    #8d8d8d

    ;
  48. }

  49. .flash-message>

    div:

    nth-child

    (

    1

    )

    {
  50. width

    :

    50px

    ;
  51. height

    :

    50px

    ;
  52. display

    :

    flex;
  53. justify-content

    :

    center

    ;
  54. align-items

    :

    center

    ;
  55. }
  56. .flash-message>

    div:

    nth-child

    (

    2

    )

    {
  57. flex-grow

    :

    1

    ;
  58. }
  59. .flash-message

    .success{
  60. border-left-color

    :

    #29af29

    ;
  61. }
  62. .flash-message

    .success

    .msg-icon

    >

    svg{
  63. color

    :

    #29af29

    ;
  64. }

  65. .flash-message

    .danger{
  66. border-left-color

    :

    #f34646

    ;
  67. }
  68. .flash-message

    .danger

    .msg-icon

    >

    svg{
  69. color

    :

    #3a3a3a

    ;
  70. }
  71. #predisplay-icons

    {
  72. display

    :

    none

    ;
  73. }

HTML

Next, create a new HTML file and save it as `index.html

`. This file encompasses the User Interface elements for the simple web page.

  1. <!DOCTYPE html>
  2. <html

    lang

    =

    "en"

    >
  3. <head

    >
  4. <meta

    charset

    =

    "UTF-8"

    >
  5. <meta

    name

    =

    "viewport"

    content

    =

    "width=device-width, initial-scale=1.0"

    >
  6. <title

    >

    Check Internet Connection</

    title

    >
  7. <link

    rel

    =

    "stylesheet"

    href

    =

    "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"

    integrity=

    "sha512-DTOQO9RWCH3ppGqcWaEA1BIZOC6xxalwEsw9c2QQeAIftl+Vegovlnee1c9QX4TctnWMn13TZye+giMm8e2LwA=="

    crossorigin=

    "anonymous"

    referrerpolicy=

    "no-referrer"

    /

    >

  8. <link

    rel

    =

    "stylesheet"

    href

    =

    "style.css"

    >
  9. <script

    src

    =

    "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/js/all.min.js"

    integrity=

    "sha512-GWzVrcGlo0TxTRvz9ttioyYJ+Wwk9Ck0G81D+eO63BaqHaJ3YZX9wuqjwgfcV/MrB2PhaVX9DkYVhbFpStnqpQ=="

    crossorigin=

    "anonymous"

    referrerpolicy=

    "no-referrer"

    ></

    script

    >
  10. </

    head

    >
  11. <body

    >
  12. <div

    id

    =

    "main-wrapper"

    >
  13. <div

    id

    =

    "page-title"

    >

    Checking Internet Connection using JavaScript</

    div

    >
  14. </

    div

    >
  15. <script

    src

    =

    "script.js"

    ></

    script

    >
  16. </

    body

    >
  17. </

    html

    >

JavaScript

Lastly, craft the JavaScript file named `script.js

`. This file houses the functionality that notifies users about their internet connection state changes. The script encompasses both the `online

` and `offline

` events.

  1. let isOnline =

    true
  2. // Offline Internet Connection Icon
  3. let netOffIcon =

    '<svg viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg" fill="currentColor" class="bi bi-wifi-off" height="30px" width="30px"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <path d="M10.706 3.294A12.545 12.545 0 0 0 8 3C5.259 3 2.723 3.882.663 5.379a.485.485 0 0 0-.048.736.518.518 0 0 0 .668.05A11.448 11.448 0 0 1 8 4c.63 0 1.249.05 1.852.148l.854-.854zM8 6c-1.905 0-3.68.56-5.166 1.526a.48.48 0 0 0-.063.745.525.525 0 0 0 .652.065 8.448 8.448 0 0 1 3.51-1.27L8 6zm2.596 1.404.785-.785c.63.24 1.227.545 1.785.907a.482.482 0 0 1 .063.745.525.525 0 0 1-.652.065 8.462 8.462 0 0 0-1.98-.932zM8 10l.933-.933a6.455 6.455 0 0 1 2.013.637c.285.145.326.524.1.75l-.015.015a.532.532 0 0 1-.611.09A5.478 5.478 0 0 0 8 10zm4.905-4.905.747-.747c.59.3 1.153.645 1.685 1.03a.485.485 0 0 1 .047.737.518.518 0 0 1-.668.05 11.493 11.493 0 0 0-1.811-1.07zM9.02 11.78c.238.14.236.464.04.66l-.707.706a.5.5 0 0 1-.707 0l-.707-.707c-.195-.195-.197-.518.04-.66A1.99 1.99 0 0 1 8 11.5c.374 0 .723.102 1.021.28zm4.355-9.905a.53.53 0 0 1 .75.75l-10.75 10.75a.53.53 0 0 1-.75-.75l10.75-10.75z"></path> </g></svg>'

    ;

  4. // Online Internet Connection Icon
  5. let netOnIcon =

    '<svg fill="currentColor" height="30px" width="30px" version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 494.45 494.45" xml:space="preserve"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <g> <g> <g> <path d="M395.225,277.325c-6.8,0-13.5-2.6-18.7-7.8c-71.4-71.3-187.4-71.3-258.8,0c-10.3,10.3-27.1,10.3-37.4,0 s-10.3-27.1,0-37.4c92-92,241.6-92,333.6,0c10.3,10.3,10.3,27.1,0,37.4C408.725,274.725,401.925,277.325,395.225,277.325z"></path> </g> <g> <path d="M323.625,348.825c-6.8,0-13.5-2.6-18.7-7.8c-15.4-15.4-36-23.9-57.8-23.9s-42.4,8.5-57.8,23.9 c-10.3,10.3-27.1,10.3-37.4,0c-10.3-10.3-10.3-27.1,0-37.4c25.4-25.4,59.2-39.4,95.2-39.4s69.8,14,95.2,39.5 c10.3,10.3,10.3,27.1,0,37.4C337.225,346.225,330.425,348.825,323.625,348.825z"></path> </g> <g> <circle cx="247.125" cy="398.925" r="35.3"></circle> </g> <g> <path d="M467.925,204.625c-6.8,0-13.5-2.6-18.7-7.8c-111.5-111.4-292.7-111.4-404.1,0c-10.3,10.3-27.1,10.3-37.4,0 s-10.3-27.1,0-37.4c64-64,149-99.2,239.5-99.2s175.5,35.2,239.5,99.2c10.3,10.3,10.3,27.1,0,37.4 C481.425,202.025,474.625,204.625,467.925,204.625z"></path> </g> </g> </g> </g></svg>'

    ;

  6. // Connection Message Container
  7. const

    flashMsg =

    document.createElement

    (

    'div'

    )

    ;
  8. flashMsg.classList

    .add

    (

    'flash-message'

    )

    ;

  9. let flashMsgText =

    `
  10. <

    div class

    =

    "msg-icon"

    >
  11. </

    div>
  12. <

    div class

    =

    "msg-txt"

    ></

    div>
  13. `;


  14. /**
  15. * Display Message when Internet Connection Lost
  16. */
  17. window.addEventListener

    (

    'offline'

    ,

    function

    (

    )

    {
  18. // Remove current Notification if do exists
  19. if

    (

    document.querySelectorAll

    (

    '.flash-message'

    )

    .length

    >

    0

    )

    {
  20. document.querySelector

    (

    '.flash-message'

    )

    .remove

    (

    )
  21. }

  22. // Clone Notification Container
  23. const

    notif =

    flashMsg.cloneNode

    (

    )
  24. // Notification Content
  25. notif.innerHTML

    =

    flashMsgText
  26. // Notification Type
  27. notif.classList

    .add

    (

    'danger'

    )
  28. // Notification Icon
  29. notif.querySelector

    (

    '.msg-icon'

    )

    .innerHTML

    =

    netOffIcon
  30. // Notification Text Content
  31. notif.querySelector

    (

    '.msg-txt'

    )

    .innerText

    =

    `Internet connection lost!

    `;
  32. document.body

    .appendChild

    (

    notif)

  33. // Update Connection Status
  34. isOnline =

    false

    ;
  35. }

    )

  36. /**
  37. * Display Message when Internet Connection Restored
  38. */
  39. window.addEventListener

    (

    'online'

    ,

    function

    (

    )

    {
  40. // Remove current Notification if do exists
  41. if

    (

    document.querySelectorAll

    (

    '.flash-message'

    )

    .length

    >

    0

    )

    {
  42. document.querySelector

    (

    '.flash-message'

    )

    .remove

    (

    )
  43. }

  44. if

    (

    !

    isOnline)

    {
  45. // Clone Notification Container
  46. const

    notif =

    flashMsg.cloneNode

    (

    )
  47. // Notification Content
  48. notif.innerHTML

    =

    flashMsgText
  49. // Notification Type
  50. notif.classList

    .add

    (

    'success'

    )
  51. // Notification Icon
  52. notif.querySelector

    (

    '.msg-icon'

    )

    .innerHTML

    =

    netOnIcon
  53. // Notification Text Content
  54. notif.querySelector

    (

    '.msg-txt'

    )

    .innerText

    =

    `Internet connection restored!

    `;
  55. document.body

    .appendChild

    (

    notif)

  56. // Update Connection Status
  57. isOnline =

    true

    ;

  58. // Automatically Remove the Notification after 5 seconds
  59. setTimeout(

    function

    (

    )

    {
  60. notif.remove

    (

    )
  61. }

    ,

    5000

    )
  62. }

  63. }

    )


Result

Explore the snapshots below showcasing the results of the provided source code:

Page UI

When Connection is Lost

When Connection Restored

There you have it! The complete source code zip file is available for free on this website. Feel free to download and customize it by clicking the Download button below this tutorial content.

Additionally, consider exploring or downloading the following:

  • Creating a Simple Input Masking using JavaScript Tutorial
  • Creating a Stopwatch Web Application using JavaScript Tutorial
  • Creating a Load More Data Feature using PHP and Pure JavaScript Tutorial

And there you have it! I trust this Guide on Checking Internet Connection with JavaScript proves helpful for your needs and will be a valuable resource for your future web application projects. Delve deeper into this website for an array of Tutorials, Free Source Codes, and Articles spanning various programming languages.

Happy Coding =)


Download
You must upgrade your account or reply in the thread to view hidden text.
 

450,270

322,965

322,974

Top