Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display onbeforeunload dialog when appropriate?

I've got an editor in javascript on my webpage and I would like to ask user if he/she wants to leave the page even if there are unsaved changes.

I know I can add custom message to the "onbeforeunload dialog" this way:

window.onbeforeunload = function() {
  return 'You have unsaved changes!';
}

(Source) but I want to display the dialog only where there really are some unsaved changes. How to do that?

Thanks!

like image 363
Martin Vseticka Avatar asked Apr 18 '10 19:04

Martin Vseticka


1 Answers

You can do something like this:

var unsavedChanges = false;
window.onbeforeunload = function() {
  if (unsavedChanges) return 'You have unsaved changes!';
}

function makeSomeChange() {
  // do some changes....
  unsavedChanges = true;
}

You can make sure to change unsavedChanges in the 'change' event handlers.

like image 193
gnarf Avatar answered Oct 17 '22 15:10

gnarf