Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
194
rated 0 times [  196] [ 2]  / answers: 1 / hits: 21438  / 14 Years ago, mon, august 16, 2010, 12:00:00

I'm currently using the jquery-form-observe plugin which uses onbeforeunload to prompt the user about unsaved changes.



But I have a scenario where I need to trigger this on a button click: the button click ultimately leads to the page changing, but I want to prompt the user before they start the process that the button click kicks off...



So is there a way to trigger onbeforeunload through jQuery or otherwise?


More From » jquery

 Answers
178

I don't know if there is a direct way to do this, but you could always emulate the browser's confirmation box yourself. Here's a simple function I cooked up based on the specs at MSDN:



function triggerBeforeUnload() {
var event = {};
handler(event);

if (typeof event.returnValue == 'undefined' ||
confirm('Are you sure you want to navigate away from this page?nn' + event.returnValue + 'nnPress OK to continue, or Cancel to stay on the current page.')) {
// Continue with page unload
} else {
// Cancel page unload
}
}


Edit: In jquery.formobserver.js, right after the definition of function beforeunload(e) { ... }, add this line:



handler = beforeunload;


Note the change in the original code: window.onbeforeunload has been replaced by handler.


[#95909] Thursday, August 12, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kourtney

Total Points: 368
Total Questions: 103
Total Answers: 85

Location: Bonaire
Member since Sat, May 1, 2021
3 Years ago
kourtney questions
Sun, Oct 4, 20, 00:00, 4 Years ago
Tue, Oct 29, 19, 00:00, 5 Years ago
Thu, Apr 4, 19, 00:00, 5 Years ago
Fri, Mar 1, 19, 00:00, 5 Years ago
;