-1

I have a customize pop up box like a lightbox or a modal box and I want to show it and prevent the page from unloading or exit when a user tries to leave or exit the page so heres my code and my try so far:

$(window).bind('beforeunload', function(){
  return loadPopup();
});

As you can see from the above codes, when a user tries to exit or leave the page, it should execute a function:

loadPopup();

But it does not work, the loadPopup(); doesn't fired. What supposed to be a problem on my above codes why it doesnt execute the loadPopup(); function?

Juliver Galleto
  • 8,831
  • 27
  • 86
  • 164
  • 6
    See the answer here: http://stackoverflow.com/questions/6063522/jquery-beforeunload. `beforeunload` doesn't work like you want it to; it just takes a string (if you return one) and pops that up. You can do *some* stuff on `unload`, though. Again, see the linked answer. – Paul Roub Jul 23 '13 at 17:53
  • What does `loadPopup` do/return? The *only* thing you can return from `beforeunload` is a string. It also will *NOT* wait for any async functions or callbacks. – gen_Eric Jul 23 '13 at 18:49

2 Answers2

1

VeeKayBee solution is correct.

Anyway you can do this with JQuery too:

$(window).bind('beforeunload', function(){
             fireOnLeave();
             return '';
});
function fireOnLeave(){
    console.log('Fired');  
}

You can check the console log and see 'Fired' string which is confirming that the function has been fired.But you have to return a string to 'beforeunload' event.

And also jquery .unload do the thing but it has been deprecated since JQuery 1.8 http://api.jquery.com/unload/

codedme
  • 616
  • 3
  • 12
0

Check this http://jsfiddle.net/Cnsyd/

I am not sure you do something using jQuery, but obviously you can do something with javaScript.

 function closeIt()
  {
    return "Any string value here forces a dialog box to \n" + 
         "appear before closing the window.";
  }
  window.onbeforeunload = closeIt;

JavaScript onbeforeunload event. It's introduced by Microsoft, but works in most browsers and click here for more details.

Believes this is the thing ultimately you requires.

kbvishnu
  • 14,760
  • 19
  • 71
  • 101