Contributing to a forum discussion or replying to a blog post is a very intensive task, so I certainly don’t take it lightly when such a task is thwarted by a careless click on a link! This happened to me! I was typing out my reply to a blog post and by mistake clicked on a link which resulted in me losing everything I had just typed!

I know there are plugins/addons out there to prevent this from happening but I really feel like it should be ‘built-in’. Browsers should have the inherent capability to save my data in such circumstances!

With that said, here’s a way to save your users the pain by warning them when they leave a page that they may have unfinished typing to attend to:

(function(){
 
    /*
     * Will test ALL textareas onBeforeUnload; if one
     * is found with text in then a warning will appear.
     * Previously, this had the problem of firing even
     * when submitting a form, so I've had to null the
     * event when a form is submitted to prevent this.
     */
 
    var textareas = document.getElementsByTagName('textarea');
        forms = document.getElementsByTagName('form'),
        fLength = forms.length,
        fOnSubmit = function(){
            window.onbeforeunload = null;
            setTimeout(function(){
                window.onbeforeunload = check;
            }, 3000);
        },
        check = function(){
            var len = textareas.length;
            while (len--) {
                if ( !textareas[len].value.match(/^(s+)?$/) ) {
                    return 'WHOA! I don't think you finished typing!';
                }
            }
        };
 
    window.onbeforeunload = check;
 
    while (fLength--) {
        var form = forms[fLength];
        form.attachEvent ?
            form.attachEvent( 'onsubmit', fOnSubmit )
            : form.addEventListener( 'submit', fOnSubmit, false );
    }
 
})();

onBeforeUnload is a proprietary event and so isn’t supported by all browsers (Opera for example) but that won’t matter – the above code should degrade harmlessly in such instances.

Here’s a run-through of what it does:

  1. Registers the check function to the onBeforeUnload event.
  2. The check function runs through all textareas and will return false if even one of them is not empty; this produces a warning if the user tries to leave the page.
  3. Because submitting a form will also trigger this onBeforeUnload event I’ve had to ‘null it’ when a form is submitted, but in the case of Ajax submission the check handler will be re-instated 3 seconds later.

Essentially, what this does is prevent users from leaving the page with unsubmitted text in a textarea element.

I’ve tested it briefly and it seems to work well in most browsers. If you encounter an inconsistency please let me know. I’ll probably implement it on this website eventually, but first I wanted to get some insight into the usability of such an enhancement…

Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!