Things couldn’t be worse when you were half way editing something and accidentally navigated away from the editing page after a whole hour of typing work. Hitting the back button of your browser neither helped, all you had done was gone anyway.
This must be remedied in some way, if you are creating an application that needs the user to input stuff, especially lengthy articles. One approach is to automate draft saving every a few minutes, the other is to warn the user before he or she either intentionally or inadvertently navigate away from the editor page. You can achieve this by a straightforward snippet of JavaScript:
var warning = false;
window.onbeforeunload = function() {
if (warning) {
return 'You have unsaved changes.';
}
}
The warning variable can be timely altered according to the editing activities by the user. For instance, it is set true if the editing field is changed or does not equal to default value, or if the user triggers the onKeyUp / onChange event of any input fields:
var editor_form = document.getElementById("form_id");
for (var i = 0; i < editor_form.length; i++) {
editor_form[i].onchange = function() {
warning = true;
}
}
This snippet must be put at the end of the page. Also, to avoid the warning when you press the form submit button, add this snippet after that:
document.getElementById("submit_button_id").onclick = function() {
warning = false;
}