2

I found the code below in stackoverflow and it works fine, but how can I capture <input type="button">?

I tried $('input').on('click'), $('input.button').on('click'), and $('button').on('click') also didn't work. Also is there any method to capture refresh event? Many thanks.

var inFormOrLink;
$('a').on('click', function() { inFormOrLink = true; });
$('form').on('submit', function() { inFormOrLink = true; });

$(window).on("beforeunload", function() { 
    return inFormOrLink ? "Do you really want to close?" : null; 
})
Blizz
  • 8,082
  • 2
  • 33
  • 53
Thomas Lee
  • 83
  • 1
  • 6

2 Answers2

2

To capture click on the <input type="button"> you can do

$('input[type=button]').on('click', function() {});

To capture refresh event you can do

window.onbeforeunload = function(e) {};

To capture refresh event with jQuery you can use unload

$(window).unload(function() {});
Kremnev Sergey
  • 332
  • 1
  • 8
  • but how to know the windows unload is refresh but not close window ? thanks. – Thomas Lee Jun 03 '15 at 09:26
  • As far as I know it might be possible, but not that trivial to implement. I'd rather reconsider your architecture, but if you really need to differentiate between refresh and close you better check out some existing questions for that. LIke this one http://stackoverflow.com/questions/291553/is-there-a-way-in-javascript-to-detect-if-the-unload-event-is-caused-via-a-refre or http://stackoverflow.com/questions/568977/identifying-between-refresh-and-close-browser-actions/13916847#13916847 – Kremnev Sergey Jun 03 '15 at 10:38
0

If I get you correctly, you want to know when a tab/window is effectively closed. Well, AFAIK the only way in Javascript to detect that kind of stuffs are onunload & onbeforeunload events.

Unfortunately (or fortunately?), those events are also fired when you leave a site over a link or your browsers back button. So this is the best answer I can give, I don't think you can natively detect a pure close in Javascript. Correct me if I'm wrong here.

saraman
  • 568
  • 7
  • 19