Continuing my trend of articles trying to show how web-applications can be made more user friendly, this article introduces another common feature to the web-app.
Almost all applications have some sort of prompt to alert the user if they try to leave before they have saved their work (Even the Notes Client has this functionality ;-). This is what we are all used to seeing when leaving a document without having saved it:
Have you ever seen anything like this on the web? Probably not. How would you do it? There are probably many fancy ways that you could track any change to a form and then set some flags to alert the user when the document is closed. There is an easier method. Internet Explorer 4 introduced the onbeforeunload event to the DOM. This can be easily used to allow the user to cancel their navigation and make sure the document is saved.
To make this happen we first need the following text in the HTML Attribute for your form :
"onbeforeunload=\"navigateAway();\""
Now, place the following JavaScript function in the JS Header (or its equivalent in R4):
var isDocBeingSubmitted = false;
function navigateAway() {
msg = "----------------------------------------------------------\n";
msg += "Your contact form has not been saved.\n";
msg += "All changes you have made will be lost\n";
msg += "----------------------------------------------------------";
//inbuilt get-out: hold control key to bypass message;
if (isDocBeingSubmitted == false && event.ctrlKey == false) event.returnValue = msg;
}
The key part is the returnValue that is assigned to the onbeforeunload event via this function. When it has a value assigned to it the event knows to prompt the user like below:
Pressing OK lets the user continue whereas Cancel returns the user to the form.
This is all well and good when the user is leaving the page by any other means than pressing the Submit button (or even the close button). When they press Submit we need to tell the onbeforeunload not to alert the user. That is why the function has the isDocBeingSubmitted global variable. If this is true then no prompt appears. To do this, the onclick event of the Submit button needs to be:
<input type="button" value="Submit" onclick="isDocBeingSubmitted = true; document.forms[0].submit();">
You may have noted that the function also checks whether the Ctrl key is being pressed. I put this in there as a little cheat to let me out of the form at any point without being reminded.
Note: Be aware of little caveats I haven't bothered to cater for. If the user presses submit and the "escapes" before the form is redirected or submitted, the JavaScript variable will be true and the function will not work anymore.
Copyright © 2000 - 2024 Jake Howlett of Rockall Design ltd. This article was printed from codestore.net