3

In my form, I have an unshowy modal. I open the modal if the user clicks on my "leave image" and I ask if he wants to leave.

Is that possible in JavaScript (Jquery ?) to "stop" the reloading or the page change to show my modal and continue the action (Reload, Next page, Prev page, etc...) if the user says yes?

I tried:

$(window).bind('beforeunload', function(){
    return 'message to show';
});

But I don't want to open the browser popup, I want mine ^^.

Karma
  • 1
  • 1
  • 3
  • 9
Sancho
  • 1,288
  • 2
  • 25
  • 50

2 Answers2

3

There is no way of stopping user from leaving the page. Only thing that can be done is confirm window.

giker
  • 4,165
  • 1
  • 18
  • 10
3

There is both window.onbeforeunload and window.onunload, which are used differently depending on the browser. You can ask them either by setting the window properties to functions, or using the .addEventListener:

window.onbeforeunload = function(){
   // Do something
}

// OR

window.addEventListener("beforeunload", function(e){
   // Do something
}, false);

Usually, onbeforeunload is used if you need to stop the user from leaving the page (ex. the user is working on some unsaved data, so he/she should save before leaving). onunload isn't supported by Opera, as far as I know, but you could always set both.

Dean Meehan
  • 2,511
  • 22
  • 36