How to warn the user before closing the page when textarea is not empty?

I am trying to reproduce the same as in stackoverflow text clouds.

EDIT: I went with something like this, having read the sentences here:

window.onbeforeunload = function()
{

    var myTextArea = document.getElementById('post_content');

    if (myTextArea.value.length > 0)
    {
        return "You haven\'t submitted your post; are you sure you want to discard it?"; 
    }

}

This seemed to work with Firefox and other browsers without causing double confirmations.

+3
source share
1 answer

Use something like:

window.onunload = function(){
   var myTextArea = [a ref to your textarea];
   if (myTextArea.value.length > 0) {
   //=>textarea contains text, ask the user:
      return confirm('You didn\'t submit your text yet! Are you sure'+
                     ' you want to navigate away from this page?');
   }
   //=>continue unloading
   return true;
}
+3
source

Source: https://habr.com/ru/post/1721065/


All Articles