Controlling the Back button using onhashchange or jquery - javascript

I need some guidance on how to have very basic control in the use of the back button.
Basically, I need to warn the user that by clicking the back button, when on my checkout.asp page, they will lose the items already there. I need to instruct them to use the navigation buttons instead.
I've had a look around a have seen mention of the onhashchange event but I could not get it to work.
I also tried the plugin by Ben Alman:
<script type="text/javascript" src="jquery/js/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="jquery/js/jquery-ui-1.8.16.custom.min.js"></script>
<script type="text/javascript" src="jquery/js/jquery.ba-hashchange.js"></script>
<script language="JavaScript" type="text/JavaScript">
$(function(){
// Bind the event.
$(window).hashchange( function(){
// Alerts every time the hash changes!
alert( location.hash );
})
// Trigger the event (useful on page load).
$(window).hashchange();
});
</script>
This only fires up the alert (with no value from the location.hash) when entering the page but I simply want to warn the user if they're leaving. If they choose to stay then let them press cancel to leave them on the same page.
Any help appreciated.

Use:
window.onbeforeunload = function() {
return confirm("you have unsaved data. ok to exit?")
})

In order to only show a warning when the back button is used, we have to eliminate the alert message when a valid source is clicked.
var showWarning = true;
window.onbeforeunload = function() {
if (showWarning) {
return confirm("you have unsaved data. ok to exit?");
}
}
function clearWarning() {
showWarning = false;
}
Now just make sure to call the clearWarning() function when an allowed button is clicked. Something like this should work:
referenceToElement.addEventListener('onClick', clearWarning(), false);
I have not tested this, but I would imagine that something like this is what you need.

Related

Pop-up when leaving website

I've been asked to have a pop-up when visitors leave the site asking them if they really want to leave. This pop-up will only show if their shopping cart has items in it.
I can easily limit the pop-up to when the cart has items, however the issue I'm having is that even clicking an internal link loads the pop-up - how can I have it so this only comes up when actually leaving the site.
<script language="JavaScript">
window.onbeforeunload = confirmExit;
function confirmExit()
{
return "some message about leaving";
}
</script>
If a link is clicked, it will tell you in e.target.activeElement. You can check if it's a link there:
window.onbeforeunload = confirmExit;
function confirmExit(e)
{
var $element = $(e.target.activeElement);
if ($element.prop("tagName") !== "A") {
return "some message about leaving";
}
}
Note: You can add additional conditions checking $element.attr("href") to make sure it displays the message for links that aren't your site.
Alright first of all: Don't do this. Please. It's super-annoying for users. Just make sure the shopping cart items are stored on the server or in a cookie so users can always go back to the site.
Looking at this related question: How can i get the destination url in javascript onbeforeunload event? it can't be done easily.
Instead of using onbeforeunload, either attach a click handler to external links on your site that shows the popup, or attach a click handler to all links that checks if the link is external or not.
Again, don't do this...
You could get the URL of a clicked link item, and check if it's on the same domain. Put this in an if not statement, with the current code inside.
you'll have to control it to enable and disable the behavior, something like this:
<script>
var beforeunload = function (event) {
var message = 'some message about leaving';
(event || window.event).returnValue = message; // Gecko + IE
return message; // Webkit, Safari, Chrome...
};
document.addEventListener('click', function(event) {
if (event.target.tagName === 'A') {
window.removeEventListener('beforeunload', beforeunload);
}
});
window.addEventListener('beforeunload', beforeunload);
</script>
this is going to remove the beforeunload event whenever a link is clicked on the page.
One way, and again, I wouldn't recommend doing this either - the user should be able to leave your site without receiving a warning - but you could unregister the event if a link has been clicked:
$('a').click(function() {
window.onbeforeunload = null;
return true; // continue
});

Jquery Show Popup only when window is closed

I am trying to display a confirmation message when the user closes the browser/tab and not when any of the links on page is clicked.
I have got the first part of displaying the message on window close working nicely but problem is that the message/alert is displayed also when user clicks on any link on the page.
I have got code from somewhere to prevent this behavior but still when ever any link is clicked the alert pops up.
Here is the code:
<script src="js/jquery-1.7.1.min.js"></script>
<script src="js/jquery-ui.min.js"></script>
<script type="text/javascript" src="js/backfix-min.js"></script>
$(document).ready(function() {
$(window).bind('beforeunload', function(e){
$("#lead-gen-modal").dialog("open");
// This line only appears in alert boxes for IE
return "Wait\! Don\'t Go\! We have a special offer for you\. Stay on this page to receive big savings\!";
});
$("a").click(function() {
window.onbeforeunload=null;
});
});
just use a global variable
and set it to false when clicking a link.
var key = true;
$(window).bind('beforeunload', function(e){
if(key)
$("#lead-gen-modal").dialog("open");
});
update :
$(document).on("click","a",function() {
key=false;
});
or if you just want to prevent closing window you can do this :
window.onbeforeunload = function(e){
if(key)
return false;
}
I think you are looking for something like this.
$(window).unload(function() {
alert("bye");
});
If that does not work on Chrome try this
$(window).on('beforeunload', function() {
return "bye";
});
jQuery API: unload() http://api.jquery.com/unload/

Jquery Exit Popup Confusion

I have the following code
<script type="text/javascript">
function PopIt() { return 'Are you sure you want to leave?'; }
function UnPopIt() { /* nothing to return */ }
$(document).ready(function() {
window.onbeforeunload = PopIt;
$('a').click(function(){ window.onbeforeunload = UnPopIt; });
});
</script>
This script works. But how do I alter it so it works like this;
1) User presses exit tab/page
2) page changes to one of my choice
3) exit popup displays with yes or no to leave
4) yes = close page, no = stay on current page
I'd like the page to change before the popup displays
Thanks.
Note: I do have control over the pages, I wish to redirect to another .php in the same folder.
Try using both onbeforeunload and onunload together like this...
function PopIt() {
return 'Are you sure you want to leave?';
}
function UnloadIt() {
window.opener.nowDoThisOpener("pass this variable along too");
}
$(document).ready(function() {
//set the function defining what should be done BEFORE unloading
window.onbeforeunload = PopIt;
//set the function defining what should be done ON unloading
window.onunload = UnloadIt;
//set all links to disable both of these on click
$('a').click(function(){
window.onbeforeunload = null;
window.onunload=null;
});
});
Note that nowDoThisOpener is a function that you can define (And obviously call whatever you want) on the parent page. And, like I've suggested, you can pass along information too.
Also, in your example you were setting an empty function UnPopIt to cancel the onbeforeunload. That's unnecessary, you can just set the onbeforeunload to null, as well as the onunload, as I've done in my example.
Previous Answer:
Could you put some kind of flag in the hash when you redirect? So instead of sending off to http://www.pageofmy.com/choice.php you sent to http://www.pageofmy.com/choice.php#1
Then on choice.php you could have...
<script>
if (location.hash=="#1") {
//show alert
}
</script>
This assumes that you have control over pageofmy.com/choice.php. If you're redirecting to some other site you don't have control over, I don't see how you can do this besides attempting to have a popup window come up (which will most likely be blocked by modern browsers)

jQuery Exit Popup Redirect?

So I've been looking around for hours, testing multiple versions, testing some of my own theories and I just can't seem to get it working.
What I'm trying to do is use alert or confirm (or whatever works) so popup a dialog when a user tries to navigate away from a purchase form. I just want to ask them "Hey, instead of leaving, why not get a free consultation?" and redirect the user to the "Free Consultation" form.
This is what I have so far and I'm just not getting the right results.
$(window).bind('beforeunload', function(){
var pop = confirm('Are you sure you want to leave? Why not get a FREE consultation?');
if (pop) {
window.location.href('http://www.mydomain/free-consultation/');
} else {
// bye bye
}
});
$("form").submit(function() {
$(window).unbind("beforeunload");
});
This is showing confirm dialog to user, want to stay or leave page. Not exactly what you looking for but maybe it will be useful for start.
function setDirtyFlag() {
needToConfirm = true; //Call this function if some changes is made to the web page and requires an alert
// Of-course you could call this is Keypress event of a text box or so...
}
function releaseDirtyFlag() {
needToConfirm = false; //Call this function if dosent requires an alert.
//this could be called when save button is clicked
}
window.onbeforeunload = confirmExit;
function confirmExit() {
if (needToConfirm)
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 taken from http://forums.devarticles.com/showpost.php?p=156884&postcount=18
Instead of using the beforeunload and alert(), I decided to check whether or not the users mouse has left the document. See code below:
$(document).bind('mouseleave', function(event) {
// show an unobtrusive modal
});
Not sure whether it will help.
You need to stop the propagation before showing the Confirm / Alert.
Please refer http://jonathonhill.net/2011-03-04/catching-the-javascript-beforeunload-event-the-cross-browser-way/
Look at the last comment.
Try this:
window.onunload = redirurl;
function redirurl() {
alert('Check this Page');
window.location.href('http://www.google.com');
}

Gmail-style Exit Message

I realize this is likely a duplicate, but I've been googling/SOing for a day now and I can't find a satisfactory answer. If there is an answer already on SO, please send me there.
I have a client that insists on having an exit message popup confirming they want to exit the site, just like Gmail does. (I've already tried arguing against it. He is immovable, so no comments about how that is bad practice please.)
I've found this code:
<script>
window.onbeforeunload = function() {
return 'Are you sure you want to exit?';
}
<script>
But it runs no matter what I do - reloading the page, clicking on the nav, etc.
I just want the message to show up when the user closes the tab/browser. I suspect it's something simple I'm missing but I'm not a Javascript expert.
Any help would be greatly appreciated.
Thanks
EDIT
Here's what is working pretty good. Thanks to all!
var isLeavingSite = true;
//This would be called on each link/button click that navigates
$('a, input[type="submit"]').click(function(){
isLeavingSite = false;
});
window.onbeforeunload = function() {
if(isLeavingSite)
return 'Are you sure you want to exit?';
}
Though it could be a fair amount of work (depending on how your site is written), you could do something like this (pseudo-code):
var isLeavingSite = true;
//This would be called on each link/button click that navigates
function GlobalLinkHandler()
{
isLeavingSite = false;
}
window.onbeforeunload = function() {
if(isLeavingSite)
return 'Are you sure you want to exit?';
}
If you're using jQuery, you can use the code below to flip the isLeavingSite flag:
$('a, input[type="submit"]').click(function(){ isLeavingSite = false; });
What'll have to do is make use a variable that you set if any link is clicked on the site, then inside the onbeforeunload event check if that variable is set meaning they clicked a link or not set meaning they're closing the tab.
You can also use that variable to simple set the href of the link; that will allow you to then check what link they clicked on inside the onbeforeunload event and allow you to check if they're clicking on a link to go to another page on your site or clicking on an external link to another site.
If your using jQuery try this Confirm before exit

Categories