How to prevent the user to change page with jQuery - javascript

I have a page with a form that is submittes via ajaxSubmit() (so, without changing the page).
My goal is that, when the user try to change page (or even to close the browser), i ask him if really want to exit the page without sending the form (exactly as gmail does).
Gmail for example do this with a window.confirm-like popup, but if it is possible, i'll like to handle it with custom messages and options.
jQuery have the unload event:
$(window).unload( function () { alert("Bye now!"); } );
but it permits me just to do something before exit the page; i need to 'block' the page exit, if the user click the relative button.
So, how to handle (and cancel) the page-exit event?

try the following. Demo here
<script type="text/javascript">
function unloadPage(){
return "dont leave me this way";
}
window.onbeforeunload = unloadPage;
</script>

It's possible bind the "onbeforeunload" event with jQuery:
$(window).bind('beforeunload', function(e) {
return "ATTENZIONE!!";
});
It works!!

Related

Preventing users from accidentally navigating away from unsaved pages

I got the snippet below from this SO post, and it works when a user tries to reload the page or close the browser etc. but if the user clicks on a link then it lets them naivagate away, and then incorrectly starts displaying the message on the wrong page. I am using pjax for the links.
$(document).ready(function () {
$('textarea').change(function () {
window.onbeforeunload = function () { return "Your changes to the survey have not been saved?" };
});
});
You should use onbeforeunload like this, inconditionally:
<script type="text/javascript">
saved=true; // initially, it is saved (no action has been done)
window.onbeforeunload = confirmExit;
function confirmExit() {
if (!saved) {
return "You did not save, do you want to do it now?";
}
}
</script>
It is not safe to handle this event only when another event is fired. The onchange event of your textarea here probably don't fire before you click on a link so the window won't handle the onbeforeunload at all. The link will work as expected: you will get redirected.
To deal with the saved flag, you could listen to what happens in your textarea, for example, when the user is actually typing something:
$('textarea').keyup(function(){
saved=false;
});
Then, if you save the data in ajax, the save button could set it back to true:
$('#btnSave').click(function(){
// ajax save
saved=true;
});
Otherwise, it will load the next page with the saved flag on.
what about something like the following?
Listening on all <a> links and then, depending on whether the variable needToSave is set to true, showing the message or letting it go.
var needToSave = false; // Set this to true on some change
// listen on all <a ...> clicks
$(document).click("a", function(event){
if (needToSave == true) {
alert("You need to save first");
event.preventDefault();
return;
}
});
UPDATE (as per Roasted's suggestion) this should trigger the unload event every time the link is clicked and perform your existing logic:
// listen on all <a ...> clicks
$(document).click("a", function(event){
$(window).trigger("unload");
});
jsFiddle here - http://jsfiddle.net/k2fYM/

when unload or exit event execute a function jQuery

I have a customize pop up box like a lightbox or a modal box and I want to show it and prevent the page from unloading or exit when a user tries to leave or exit the page so heres my code and my try so far:
$(window).bind('beforeunload', function(){
return loadPopup();
});
As you can see from the above codes, when a user tries to exit or leave the page, it should execute a function:
loadPopup();
But it does not work, the loadPopup(); doesn't fired. What supposed to be a problem on my above codes why it doesnt execute the loadPopup(); function?
VeeKayBee solution is correct.
Anyway you can do this with JQuery too:
$(window).bind('beforeunload', function(){
fireOnLeave();
return '';
});
function fireOnLeave(){
console.log('Fired');
}
You can check the console log and see 'Fired' string which is confirming that the function has been fired.But you have to return a string to 'beforeunload' event.
And also jquery .unload do the thing but it has been deprecated since JQuery 1.8
http://api.jquery.com/unload/
Check this http://jsfiddle.net/Cnsyd/
I am not sure you do something using jQuery, but obviously you can do something with javaScript.
function closeIt()
{
return "Any string value here forces a dialog box to \n" +
"appear before closing the window.";
}
window.onbeforeunload = closeIt;
JavaScript onbeforeunload event. It's introduced by Microsoft, but works in most browsers and click here for more details.
Believes this is the thing ultimately you requires.

Detect page unload with javascript

I have a cancel button, that does an ajax and then refreshes page contents, and when navigating away I want to trigger the button, but I don't want it to refresh anything in the UI.
I thought of using a global variable, placed in the window object, but that does not seem very nice:
$(".cancel").bind("click", function(e) {
e.preventDefault();
tellTheServerThatUserCanceled(); // ajax call
if (!isUnloading) refreshUI();
});
$(window).bind("unload", function(e) {
isUnloading = true; // this is disgusting, I don't want to do this
$(".cancel").trigger("click");
}
Is there any official way, or another more elegant way, or I shouldn't be worried about using global variables?
EDIT:
The unload event code does not know what exactly it must do, because the page can have multiple edit panels, with multiple cancel buttons. All it knows is that it must trigger the cancel buttons of each panel.
I find its nicer not to run your code in jQuery's anonymous functions, but rather have them call functions that are sharable. Something like this illustrates the general idea:
function doCancel(e, isUnloading){
e.preventDefault();
tellTheServerThatUserCanceled(); // ajax call
if (!isUnloading) refreshUI();
}
$(".cancel").bind("click", function(e) {
doCancel(e, false);
});
$(window).bind("unload", function(e) {
doCancel(e, true);
}

control window.onbeforeunload event

From out of curiosity can i Control window.onbeforeunload event like check if the user decided to leave the page or stay in it and can I raise an alert or some function based on his decision if yes please tell me
<script type="text/javascript">
$(window).bind("beforeunload",function(){
if(//stay on page)
alert("i want to stay on the page");
else //leave page
alert("i want to leave the page");
});
</script>
I understand that window.onbeforeunload is an event that give the user a message to tell him that maybe you forget to do something before you leave but this quest is just out of curiosity and thank you
You can ONLY return a string which will show a dialog confirmation displaying the string you returned (But with additional ok/cancel buttons to confirm the action).
<script type="text/javascript">
$(window).bind("beforeunload",function(){
return 'Are you sure you want to leave this page?';
});
</script>
You cannot get the result of onbeforeunload. Also, even if you somehow managed to figure out a way to get the result, you wouldn't be able to raise an alert. You could probably run another function.
The showModalDialog(), alert(), confirm() and prompt() methods are now allowed to do nothing during pagehide, beforeunload and unload events.
Put a timer of one second. Clear it on unload. Should work, but didn't test it.
window.addEventListener('beforeunload', function (event) {
var timeId = setTimeout(yourFunctionIfTheUserStays, 1000);
window.addEventListener('unload', function (event) {
clearTimeout(timeId);
})
return 'Are you sure you want to leave this page?';
});

Custom beforeunload prompt with javascript

I'm trying to setup an exit survey so that when a user leaves our checkout page they are prompted asking them why they're leaving.
Is this possible?
I've spent some time on Google but it appears as though the only solution is a simple browser-controlled confirm-like prompt. Is this true?
update
The following confirm dialog never appears, the page just changes or exits. How can I prevent the page from changing/exiting until I wait for a user's response. I guess I should ask, how can I resume a user's exit/page change action after using e.preventDefault(); ?
jQuery(window).bind('beforeunload', function() {
return function () {
alert('x');
setTimeout(50000, function () {
confirm('you sure?');
});
}();
});
If you are using jQuery you can just do
$(window).unload( function() {
//statements
});
You can do anything you want in the onunload event of the browser:
body.onunload = function() {
foo();
bar();
}
As suggested by levu, use the onunload event in combination with a custom modal dialog, such as thickbox - http://jquery.com/demo/thickbox/

Categories

Resources