A user can leave a page in many different ways. First of all they can simply click a web page link to another internal or external URL. This is the simplest action and it triggers a click event which can be responded to with a script and even canceled entirely. The following for example will show a message when the user click an external link(indicated by the presence of the class "external").
$(document).ready(function()
$("a.external").click(function() {
alert("Leaving to " + $(this).attr("herf"));
});
});
But how can we react to other types of navigation such as the browser back and forward buttons, page reload, url change, and page close events. This can be done to a limited extent with the onbeforeunload event though we can't actually see what action the user preformed to leave the page. There is a further problem here though. Simply adding a event handler on the onbeforeunload will also run when the user clicks links inside the site witch we may not want. With that in mind the following code will attach a event handler to the onbeforeunload but will discard it when it detects that a internal or external link was clicked witch can be captured normally. Additinal link level logic can then be added to the link click events.
$(document).ready(function() {
// Listen for the unload event and return a warning/run custom code.
window.onbeforeunload = function (event) {
if(true) {
return "You have items in your cart.";
}
}
// If disable event on link clicks that are not hash links, mailto, or javascript calls.
$("a[href]:not([href^=#],[href^=mailto],[href^=javascript])").click(function(){
window.onbeforeunload = null;
});
});
This bit of code will allow for a script to run when the user tries to leave the page and can warn about unsaved changes, etc. Be warned though that this is only a prompt and furthermore that in most cases this type of alert/warning to users may be irritating. It should only be used to trigger warnings about unsaved changes, etc. Also there are some other limits here. For example you can't redirect the browser to a new url on page exit as the browser is already changing pages.
No comments:
Post a Comment