Sorry if duplicate, but I don't understand how I can use the basic approach in my case.
I need to hide some div, when user presses back button in browser. That is all what I need. The page must not to be reloaded. I tried this way:
window.onpopstate = function (event) {
event.preventDefault();
alert("Back button pressed");
myDiv.style.display = 'none';
}
But this doesn't work at all. Even alert doesn't fire. And the browser goes back as always.
How to make it work? First of all this must works in mobile browsers.
Will the using of window.location.hash trigger page reloading or not?
Short answer: You can't change it.
Long answer:
You should first set a State then get it with event handler.
So, simply, when user clicks on a specific section of your document, for example a <a>, you set a State then when he clicks on back button ( of browser ) you've got a fired event.
someElement.addEventListener( 'click', function( e ) {
history.pushState({ state: 'someElement was clicked' }, 'title', 'some-element.html' );
})
Now, as back button pressed, you've got an alert ( as presented in your question ).
For furthur information check here: Manipulating the browser history( mdn )
No, changing the location hash will not do a page reload (this is where all Single Page Applications are based upon.
Preventing the behaviour after the back button is clicked (which will trigger a page reload) is not really an option. Best you can do is warn the user:
window.onbeforeunload = function() {
return 'Sure you want to leave?';
};
Related
I have an action planned on a space bar click. It does happen.
// when space bar is pressed
do-something; // Applied on the $(document).keypress..
But, when I press space bar, along with the event/action that has to be triggered, modal load/shows up again. Why is it so? I have tried to prevent modal from loading again :
$('#goal').on('hidden.bs.modal',function() {
$(document).focus(); // Get the button that triggered modal
// out of focus
});
But the document, doesn't get focus and the button that triggered modal-load remains in focus until I click on the screen to bring the document back to focus. How could I prevent modal from loading again on space bar press?
I also tried the blur() function on button that triggers modal. But it doesn't help?
Using $(document).focus(); will have no effect, because document is not a focusable element, it's actually not an element at all. Try using document.activeElement to get the active element and blur it.
document.activeElement.blur();
To do this, you will need to listen for the event when the modal is closed, hidden.bs.modal, since Bootstrap will automatically return the focus to the button on close.
Example (Live):
$(document).on('hidden.bs.modal', function() {
document.activeElement.blur();
});
Alternately, you could set the focus to a focusable element in the model itself if one exists. This would probably give the most-pleasant user experience.
It might be due to default focus on an element which might be causing this. Tried event.preventDefault(); ?
// when space bar is pressed
event.preventDefault();
do-something; // Applied on the $(document).keypress..
This is a bit hard to answer without seeing more of your code or, even better, a jsfiddle that demonstrates your problem.
But in general, you can prevent the space bar keypress from having any side effects by returning false from the jquery event handler function to indicate that you've consumed the event.
So (guessing what your event handler looks like)
$('...').keypress( function(event) {
if ( event.which == 32 ) {
doSomething();
return false;
}
});
Hope this helps. If not, please give a bit more details.
You can avoid the button gaining focus this way:
$('#yourButtonId').focus(function(){
$(this).blur();
});
I tried this in the jsFiddle you posted and it works, the space bar doesn't open the modal anymore.
When i click Mobile browser back button, It should say the confirmation box like
"Are you wants to leave this page"
If the user click "OK" I need to trigger some function.
It's working fine. But when i click "Cancel" it's not staying on the same page. I tried the below code. But am not able to success.
var unloadEvent = function (e) {
var confirmationMessage = "Are you want to leave this page";
(e || window.event).returnValue = confirmationMessage;
if(confirm(confirmationMessage)) {
//some JS function
} else {
return false;
}
};
window.addEventListener("beforeunload", unloadEvent);
Please help me to solve this issue.
Thanks
You can't modify the default dialogue for onbeforeunload, so your best bet may be to work with it.
window.onbeforeunload = function() {
//Do some other stuff here..
return 'You have unsaved changes!';
}
Here's a reference to this from Microsoft:
When a string is assigned to the returnValue property of window.event, a dialog box appears that gives users the option to stay on the current page and retain the string that was assigned to it. The default statement that appears in the dialog box, "Are you sure you want to navigate away from this page? ... Press OK to continue, or Cancel to stay on the current page.", cannot be removed or altered.
The problem seems to be:
When onbeforeunload is called, it will take the return value of the handler as window.event.returnValue.
It will then parse the return value as a string (unless it is null).
Since false is parsed as a string, the dialogue box will fire, which will then pass an appropriate true/false.
The result is, there doesn't seem to be a way of assigning false to onbeforeunload to prevent it from the default dialogue.
Additional notes on jQuery:
Setting the event in jQuery may be problematic, as that allows other onbeforeunload events to occur as well. If you wish only for your unload event to occur I'd stick to plain ol' JavaScript for it.
jQuery doesn't have a shortcut for onbeforeunload so you'd have to use the generic bind syntax.
$(window).bind('beforeunload', function() {} );
This answer is suggested by Owen on the question: override onbeforeunload
Thanks Owen.
SETUP - Large search with many criteria as a POST via a html submit button, it can take several seconds before the first byte is sent by the server / results page starts loading.
http://api.jquery.com/unload/ is now deprecated (as of version 1.8), and I'm searching for the CORRECT way to do the following...
When someone clicks the search button, I give the user a little feedback by setting the button text to "Searching...", then allow the submit to continue (return true):
$('#dosearch').click(function() {
$(this).html('<i class="icon-spinner icon-spin"></i> Searching...');
return true;
});
During unload I'm currently doing this:
$(window).unload(function() {
$('#dosearch').html('<i class="icon-search"></i> Search');
});
I tried binding to beforeunload, but that fires as soon as the submit happens (bad), not as soon as the browser begins rendering the new page (good).
The problem is if they click search and then click the BACK button on their browser. If they do that, then the Searching... text is still shown.
What is the correct / proper way to do what I'm attempting here?
NOTE: (The reason for the I tag is that I'm using font awesome).
Binding an empty event handler to unload seems to work, but it's kind of a hack.
$('#dosearch').click(function() {
$(this).html('<i class="icon-spinner icon-spin"></i> Searching...');
return true;
});
$(window).on("load", function(){
$('#dosearch').html('<i class="icon-search"></i> Search');
});
$(window).on("unload", function(){
// Leave this blank handler here or onload won't fire on IE or FF when you click back button
});
See this question for explanation.
If the user goes back in history, it means it renders the page new or not? So you could, whenever the page is loaded, reset the value to what you want to.
Could that be something?
I have an onbeforeunload event :
$().ready(function() {
window.onbeforeunload=function() { return "haha" };
});
And my links are like this (ajax web site) :
<a href="#pageX" />
But the onbeforeunload is never called. What can i do ?
Thanks
I'm guessing since you're trying to bind to the onbeforeunload and return a string, that you're looking to provide the user with an "Are you sure you want to leave this page" dialog on an AJAX site.
In which case you probably need to go about this a little differently by binding a click handler onto the links. So you can prevent the hash change until the confirmation is made.
Something like:
$('a[href^="#"]').live('click',function(e){
if( //should we be confirming first? ) {
//put your confirmation code here either using default JS windows or your own CSS/jQueryUI dialog boxes
// this code should either cache the url of the link that was clicked and manually update the location with it when the user confirms the dialog box (if you're using JQUI windows) or simply use JS confirmation boxes and based on the response, all you need to do is return; and the link click will handle normally
e.preventDefault(); //prevent the link from changing the hash tag just yet
e.stopImmediatePropagation(); //prevent any parent elements from firing any events for this click
}
} );
Don't get me wrong, but are you serious ?
That link just refers a hash-tag, hence, it will not leave the current site and there will be no call to onbeforeunload nor unload.
If there is any *click event handlerbound to that anchor aswell, there must be something in the event handler code which really forces the current site to get unloaded (location.href` for instance).
If you just switch HTML via Ajax, there is no onbeforeunload aswell.
You could bind a handler to the onhashchange event (check browser compatibilty) but that would fire for any change that happens in your url/hash.
You're probably looking for the onhashchange event:
https://developer.mozilla.org/en/DOM/window.onhashchange
I'm developing one of those warning windows that tells the user that they may have unsaved data, but I only need it to warn them if they're leaving the page. Currently it does so on refreshes, postbacks, etc. I was wondering if there was any way to tell how the page was unloaded or otherwise get more details about what the user is doing to unload the page. (jquery solutions welcome).
Code for reference:
window.onbeforeunload = function () {
if (formIsDirty) {
formIsDirty = false;
return "Are you sure you want to navigate away from this page?";
}
}
on beforeunload event we can do below things:
We can pass event as a parameter to the function as in above answer.
Now we can use this event for available information attached to this
event.
And we can access Document level variables.
For example document.activeElement will give you the last element you clicked that caused the page unload.
Hope this helps!!
I think that the active element is not a valid solution.
I can't comment the "open and free" solution, I dont have reputation.
document.getActiveElement gets the currently focused element in the document. If a link have the focus and I press F5 or I close the tab the active element is the link.
Short answer: There's no easy way to find out what is causing onbeforeunload to fire.
Long answer: Inside your window.onbeforeunload handler you can access the window.event object, which may have some useful properties to determine how the window is closing.
For example, if window.event.srcElement is an anchor tag, then you know that the onbeforeunload event is firing by an anchor tag being clicked.
Refer to the event and onbeforeunload pages on MSDN for more properties.
Edit: some more info I have stumbled across -
If you want to ignore ASP controls that cause post-back, you can interrogate the '__EVENTTARGET' hidden input. If this input has a non-empty string value, then the page is being posted back by an ASP control.
You could also check the keyCode property (if F5 has been pressed, causing a refresh) or the mouse position to see if the X (close) button has been clicked.
I was running into a simular issue when a user was hitting enter from an input field on a form. The form was being submitted thus firing off the onbeforeunload event. I tried setting a flag to avoid showing the message on the keydown event on the input, filtering on the enterkey code. This wasn't getting triggered until after the onbeforeunload event was firing and therefore the flag wasn't getting set.
I then looked into the _EVENTTARGET as jbabey suggested. If the form was being submitted there would be a value in that field, if it was being refreshed there wouldn't.
Therefore, doing a simple check to see if there was value in the _EVENTARGET field in the onbeforeunload event could determine if the input from the form was causing the postback.
Here is my code.
window.onbeforeunload = function (e) {
if ($('[id$=__EVENTTARGET]').val().indexOf('btnValidateMaterials') != -1) {
confirmExit = false;
}
if (DateOrQtyHasChanged() && confirmExit) {
if (/Firefox[\/\s](\d+)/.test(navigator.userAgent) && new Number(RegExp.$1) >= 4) {
var message = $('[id$=hfLeaveMessageFF]').val();
if (confirm(message)) {
history.go();
}
else {
window.setTimeout(function () {
window.stop();
}, 1);
}
}
else {
var message = $('[id$=hfLeaveMessage]').val();
return message;
}
}
}