Let's say I have an update
page in HTML5 and if the user edited a field, I want to show a pop-up whenever the user will exit the page (by clicking on another link) without clicking the update
button. The pop-up will confirm if the user wants to save his edits or if the user declined, simply continue on the link he clicked before. How to achieve this in HTML5/JavaScript? Is there any function that preempts redirects? Thanks.
Asked
Active
Viewed 61 times
0

oikonomiyaki
- 7,691
- 15
- 62
- 101
1 Answers
2
Use the onbeforeunload
event.
Check out the demo: onbeforeunload Demo
JS code:
<script language="JavaScript">
window.onbeforeunload = confirmExit;
function confirmExit()
{
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
</script>

KoenW
- 453
- 1
- 3
- 13
-
Thanks, this shows an alert box. How about if I want to use a custom pop-up I created instead of a default JavaScript alert? – oikonomiyaki Oct 30 '14 at 07:55
-
You can't. Here's some extra information: http://stackoverflow.com/a/276739/3310441 – KoenW Oct 30 '14 at 08:09
-
As mentioned in the post above, you can use jQuery's 'beforeunload' event: $(window).bind('beforeunload', function() { //dialog here } ); but this may cause problems – KoenW Oct 30 '14 at 08:13