Wednesday, April 22, 2009

Are you sure you want to navigate away from this page?

Scenario: you've been tasked with creating a simple web-based time-sheet application, so employees can log what percentage of their time is devoted to which project. Now, this hardly qualifies as "Bioinformatics," a domain claimed by both your job title and personal aspirations, but it's a small company and they pay your rent.

So you build the little beasty, and your cube-neighbor sits down to fill out a time-sheet. She spends 7 minutes selecting options and punching in percentages, and then realizes she wants to trim one field from 15% to 10%, clicks her mouse 4 pixels too far to the right putting the page, and not the text input, into focus, and hits Backspace -- equivalent to the back button.

There go her 7 tedious minutes of form-filling -- this app isn't sophisticated enough to autosave a draft in real-time, after all.

Enter the onbeforeunload function.

I've borrowed from this guy a bit, but here's the code:
var confirm_exit = true;

window.onbeforeunload = function() {
if( confirm_exit )
return "";
return; };

$(document).ready( function() {
$("#id_theform").submit( function() { confirm_exit = false; } );
} );
Originally, I'd planned to skip the ugly global variable and simply re-bind the onbeforeunload function, but apparently you can't rebind like that.

1 comment:

Anonymous said...

hOLy DAYUMz thta h3lped a l07 man thnx. ROCK ON FREVR!!!! COMP TECH 4 LYPH haha jkjk lol. nah just jokes. but really, man KUDOES!!!!!! A++ most def.