JQuery onunload does action if button is clicked

I have a small website that has jQuery on its side.

I have a page where I need to perform some AJAX action before the page is unloaded, but this action may not work if a certain button was pressed.

I tried to do this:

<body onbeforeunload="myaction();"> 

But how do you know if a button is pressed?

+4
source share
2 answers

You can also bind onbeforeunload to jQuery :

 myCounter = true; $(window).load(function(){ $('#mytest').bind('click', function(){ myCounter = false; }); }); $(window).bind('beforeunload', function() { if (myCounter) { $.ajax({ type: 'POST', url: 'mytest.php' }); } }); 
+1
source
 var globalClickVariable = false; $('#my-button').click(function() { globalClickVariable = true; }); <body onbeforeunload="if(!globalClickVariable) { myaction(); }"> 
+4
source

All Articles