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=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!"); 
});

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 et.al. span.style.cssText="z-index:99;font-size:18px;background:#FFF1A8;top:0";

  • Set it's 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!

Share this