1

I currently have a website that uses a cart-like system for temporarily holding enquiries. I currently use the Javascript onunload function to stop the user from leaving the page and loosing his/her enquiries in the cart.

The only problem I have is that the cart spans across multiple pages which is fine because it is session based but whenever I try to change page the onunload even pops up and can be very annoying.

Is it possible to set the onunload event to the close button on the browser so it only shows when they try and close it possibly?

I hope we can find something as re-designing the site is not really an option,

Thank you

Alex
  • 493
  • 1
  • 6
  • 11
  • 1
    Where are the temporary enquiries being stored? How are they being passed to the next page? If you store them in [session storage](https://developer.mozilla.org/en-US/docs/DOM/Storage#sessionStorage) they would be available throughout the session and would automatically go away when the browser/tab was closed. No need to use `onunload` then. – Useless Code Mar 14 '13 at 09:11
  • They are stored in a session, and each page has a cart-like div which just loads and formats the session. The site does not open new windows or tabs. – Alex Mar 14 '13 at 09:16
  • When you say in a session, I'm assuming from your comment below you mean a PHP session? It would help to be more specific since you didn't mention PHP in the question nor tag it with PHP. – Useless Code Mar 14 '13 at 09:19
  • Ah, yes. A PHP session, sorry about that I didn't think as it wasn't originally about PHP. Items are put into an array in a session. – Alex Mar 14 '13 at 09:22

1 Answers1

2

Perhaps you could use a global variable to tell whether you are leaving the page for the next step in the cart.

For example, in the onclick or onsubmit event for the 'next' button in each cart page, you could set a global variable indicating that you should let the user navigate away from the page. And then in the onunload event you would check whether this global has been set, only showing the warning if it hasn't.

grc
  • 22,885
  • 5
  • 42
  • 63
  • Brilliant comment, I should have thought of this! I wonder if adding a new variable into php to catch the url would slow it down and this could hide or show the javascript? If that makes sense.. – Alex Mar 14 '13 at 09:11
  • It wouldn't need to be a global if you encapsulated the variable and all the handlers that use it in the same [self invoking function](http://stackoverflow.com/a/3597102/778975). It's best not to expose global variables in JS unless you need to, especially if you will ever be using JS written by someone else on your page (JS libs, social widgets, etc). – Useless Code Mar 14 '13 at 09:38