HTML5+JS offline/online notification

Before diving into HTML5+JS offline/online notification, try the demo or if you are lazy see the video

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:

function notify(text) { 
span.innerHTML=text;"z-index:99;font-size:18px;background:#FFF1A8;top:0";'fixed'; - 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(" are offline!"); 

Lets dismantel the code!

In simple steps:

  • Create a span element. span=document.body.appendChild(document.createElement('span'));

  • Set it's content to what ever you want to notify the user about. span.innerHTML=text;

  • Give it some style, with required background, font-size"z-index:99;font-size:18px;background:#FFF1A8;top:0";

  • Set it's position (fixed here).'fixed';

  • Bring it to the center! ( So it looks good?) - 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!

Share this