You need to perform a check inside the handler, for example:
window.onbeforeunload = function(){ if(!$buttonpressed){ return "Your changes may not be saved."; } }
It currently binds window.onbeforeunload when your code is running, because $buttonpressed is false when it starts ... it doesn't matter if it changes later since you already bound the handler. An alternative is to make it a little easier, for example:
window.onbeforeunload = function(){ return "Your changes may not be saved."; } $j(".Actions input").click(function(){ window.onbeforeunload = null; });
It just removes the handler on click . A more appropriate event to handle other dispatch cases would be to attach to the submit event, for example:
$j(".myForm").submit(function(){ window.onbeforeunload = null; });
source share