Reputation: 343
I want to know how can I display a confirmation box when the users try to get out of the page, like this one here in StackOverflow when you try to close the "Ask Question" page.
Thanks you in advance.
Upvotes: 3
Views: 857
Reputation: 5849
In javascript, attach a function to window.onbeforeunload
, like so:
window.unbeforeunload = function (e)
{
// return (prompt ('Are you sure you want to exit?'));
// EDIT: Amended version below:
var e = e || window.event;
if (e) e.returnValue = 'Your exit prompt';
return 'Your exit prompt';
}
EDIT: As the comments below indicate, I had misunderstood the working of the event. It should now work as intended.
Ref: window.onbeforeunload (MDC)
Upvotes: 3
Reputation: 8610
probably a dupe: How do you prevent a webpage from navigating away in JavaScript?, but you can do this by adding an delegate to the window.onbeforeunload event
<script type="text/javascript">
window.onbeforeunload = function() {
//will show a dialog asking the user if
//they want to navigate away from the current page
// ok will cause the navigation to continue,
// cancel will cause the user to remain on the current page
return "Use this text to direct the user to take action.";
}
</script>
Update: doh! updated code to do what the OP really wanted :D
Upvotes: 2
Reputation: 10377
Actually, all that is necessary is this:
window.onbeforeunload = function(){ return "You should save your stuff."; }
This is also kind of a dupe of this: How to show the "Are you sure you want to navigate away from this page?" when changes committed?
Upvotes: 6
Reputation: 187070
You can use the window.onbeforeunload event to catch this. If there is any value inside the textarea then an alert message is shown.
Upvotes: 1
Reputation: 8734
You want to catch the onbeforeunload
event of window
. Then if you return a string, the browser will display your message in a prompt. Here's an article with sample code.
Upvotes: 1
Reputation: 83254
That's browser based.
As long as you implement <form>
tag, and you type in something in the form, and in Google Chrome, it will prompt you that message.
Upvotes: -4