Execute code after onbeforeunload modal
Do you want to execute some JS code after the visitor clicks on 'Stay on this page' button in a onbeforeunload modal?
I found a really nice hack to do so. It pushes the code in the next UI cycle using setTimeout which gets executed as soon as the modal closes and execution resumes:
$(function() {
$(window).bind('beforeunload', function() {
setTimeout(function() {
setTimeout(function() {
$(document.body).css('background-color', 'red');
}, 1000);
},1);
return 'are you sure';
});
});
Watch it live here.
Source: http://stackoverflow.com/a/4651049/891962
Written by Kushagra Gour
Related protips
3 Responses
Just forked your script :)
http://jsfiddle.net/yM5n5/1/
You can shorten and/or abstract that - you can remove some stuff and make that a function to use it in a lib or so:
http://jsfiddle.net/mkzero/LumBj/10/
But thank you for pointing that out. Might come in handy some day.
@mkzero cool!