HTML5+JS offline/online notification

Submitted by hemanth on Tue, 06/05/2012 - 19:17

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;px;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;px;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!

spacer
  • hemanth's blog

Recent blog posts

  • gem list to gemfile
  • Packing ruby2.0 on debian.
  • Made it into The Guinness Book!
  • to_h in ruby 2.0
  • Filter elements by pattern jQuery.
  • Better HTML password fields for mobile ?
  • Grayscale image when user offline
  • nth-child CSS pseudo-class Christmas colors
  • EventEmitter in nodejs
  • Live reload with grunt
more
gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.