0

I'd like to make an exit popup on my website. I've prepared my modal but can't find "a good way" to detect a moment when a user is about to leave the website. I've read some other posts on this subject and found this piece of code:

$(document).ready(function() {
  $(document).mouseleave(function(e) {
    if(e.clientY < 0) {
      $('#exit').modal('show')
    }
  });
});

Unfortunately this solution doesn't work on IE and Edge. What's the better way of doing it?

UPDATE: Let me be more precise. I want to achieve something like this. I assumed that the best way is to detect when a mouse leaves a document.

always_bloo
  • 165
  • 5
  • 13

2 Answers2

1

Typically this is done using the onbeforeunload event on the window. This should be assigned to a function that returns the text you wish to display to the user when they are leaving the page. For example:

window.onbeforeunload = function () {
    return "Are you sure you want to leave?"
}

This will result in a confirmation window when the user tries to leave the page for any reason. If you don't want it to display on internal links, you will need to use javascript to unassign the event before the navigation occurs.

Will P.
  • 8,437
  • 3
  • 36
  • 45
0
window.onbeforeunload = function () {
    // do stuff with your modal here
}

do what you want inside the callback function, but the onbeforeunload event is the one you will want to handle

geekzster
  • 559
  • 8
  • 21
  • This doesn't work. It shows it and closes the browser. – Praveen Kumar Purushothaman Dec 20 '16 at 20:49
  • 1
    before unload is when you're leaving the page, not moving the mouse away. – jdmdevdotnet Dec 20 '16 at 20:50
  • you'll want to work with whatever the #exit modal is - we don't know that from what you posted. it's just an example. – geekzster Dec 20 '16 at 20:52
  • @AlGoreRhythm, "before unload" is when OP said they're trying to trigger a popup. this code still won't work, but not for the reason you mentioned. – Dan O Dec 20 '16 at 20:52
  • I see your point, but if you look at comments `That code basically checks to see if the mouse cursor is above the top of the document window. Is that what you're trying to do??` and the OP's response `Yes, it is. As I said - the result is fine, but it's doesn't work on all browsers`. I think the OP is confused on what he wants. – jdmdevdotnet Dec 20 '16 at 20:55
  • @Al for the record those comments were added after (or the same time as) I posted my answer. but I agree - not sure at this point what behavior the OP wants, so we'll see – geekzster Dec 20 '16 at 21:00