Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

capture user leaving page with jquery

Tags:

jquery

I want to implement a feature that if a user is navigating away from a page and they have unsaved changes on the page they get alerted. So I need to capture the event that fires to movement from the page and perform custom actions on it. Hoping to do this with jquery. Any tips?

like image 529
amateur Avatar asked Nov 06 '10 02:11

amateur


1 Answers

You can't do this with jQuery, but you can attach a handler to window.onbeforeunload with plain JavaScript:

window.onbeforeunload = function() {
  return "You have unsaved changes, do you want to leave?";
};

Just bind this when they make changes to any inputs, and unbind it when hitting the save button (so it won't prompt on submission) with window.onbeforeunload = null;.

like image 179
Nick Craver Avatar answered Oct 11 '22 09:10

Nick Craver