Monday, February 27, 2012

Page Visibility in JavaScript

The other day I was reading a post discussing the Page Visibility API and thought this could be a really useful tool for developers. Currently it is still being “standardized” by the W3C but it is available to use in many current browsers using engine specific-prefixes (I will stay out of the red hot prefix debate for the moment). Suffice it to say, you can get it to work on most modern browsers using a combination of prefixes.

The Page Visibility API allows you to determine when your page has moved to the background or the browser has been minimized. Some uses I could think of are things like setting your status as away in browser-based chat clients, pausing a game or video, stopping or starting background processes or even persisting data and settings.
In this simple example I decided to look at a problem I have encountered myself that the Page Visbility API might be able to solve in conjunction with the Local Storage API. The problem is that sometimes when filling out a complex form I get pulled away and forget to finish. In some cases, my session may time out and I could end up losing all the form data I already started. So, my thought was, what if I detect when you’ve left the form and persist your form entries to local storage. This way, when you return to the form, even if the page has been closed or you’re forced to re-login, your form entries won’t be lost.

It turns out this is really easy to do. Let’s look at the code from my example page (view source for the full code). Please note, that for simplicity’s sake, I made this to run specifically in Chrome, but if you borrow this script from Sam Dutton’s example, you could easily modify this to run across browsers. The other thing is, I am also not using jQuery here. I know the tendency is to do so even for simple examples like this but (sorry to rant for a sec) I feel a lot of developers include it unnecessarily. As you’ll see, simple DOM manipulation can be done without it.
 Read More..

For Free consultation on regarding Flex Development, Flex Developers Flex Expert, Flex Programmers log on to http://www.dckap.com

No comments:

Post a Comment