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!");
});
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!
#javascript#html5
About Hemanth HM
Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.