---
title: "HTML5+JS offline/online notification"
description: "With HTML5 and some JavaScript magic, it’s very easy for a webpage/webapp to indicate if the user is offline or online in JS."
url: "https://h3manth.com/scribe/html5js-offlineonline-notification/"
canonical_url: "https://h3manth.com/scribe/html5js-offlineonline-notification/"
markdown_url: "https://h3manth.com/scribe/blog/html5js-offlineonline-notification.md"
publishDate: "2012-06-05T00:00:00.000Z"
author: "Hemanth HM"
category: "javascript"
tags: ["javascript","html5"]
word_count: 238
reading_time_minutes: 2
x_markdown_tokens: 595
content_signal: "ai-train=yes, search=yes, ai-input=yes"
---

# HTML5+JS offline/online notification

> With HTML5 and some JavaScript magic, it’s very easy for a webpage/webapp to indicate if the user is offline or online in JS.

Before diving into HTML5+JS offline/online notification, try the [demo](http://h3manth.com/demo/notification.html) or if you are lazy see the [video](http://youtu.be/V8z-QO9RwY0)

With evolution of HTML5 and some JavaScript magic, it's very easy for a webpage/webapp to indicate if the user is offline or online.

**But what's the use?!**

* Avoiding user hitting the refresh button!
* As a responsible app, it's neat if it does so?
* Can indicate the user when to try again, with timeouts.
* Notify me, if you got something ;)

**So I managed to beget some raw offline/online notification code:**

```javascript
function notify(text) { 
    span = document.body.appendChild(document.createElement('span')); 
    span.innerHTML = text;
    span.style.cssText = "z-index:99;font-size:18px;background:#FFF1A8;top:0";
    span.style.position = 'fixed';
    span.style.left = ((document.body.clientWidth - span.clientWidth) / 2) + "px"; 
    window.setTimeout(function() { document.body.removeChild(span); }, 3000);
}

window.addEventListener('online', function(evt) { 
    notify("And....we are back!"); 
});

window.addEventListener('offline', function(evt) { 
    notify("OOPS....you are offline!"); 
});
```

**Let's dismantle the code!**

**In simple steps:**

* Create a span element: `span = document.body.appendChild(document.createElement('span'));`
* Set its content to whatever you want to notify the user about: `span.innerHTML = text;`
* Give it some style, with required background, font-size etc.: `span.style.cssText = "z-index:99;font-size:18px;background:#FFF1A8;top:0";`
* Set its position (fixed here): `span.style.position = 'fixed';`
* Bring it to the center! (So it looks good?): `span.style.left = ((document.body.clientWidth - span.clientWidth) / 2) + "px";`
* Set timeout, for it to disappear forever: `window.setTimeout(function() { document.body.removeChild(span); }, 3000)`
* Bind window, with offline and online events: `window.addEventListener('online'/'offline'...`
* Indeed, my fav step -> Enjoy!
