I love jQuery for many reasons, the primary one being that it abstracts all the cross-browser pain of writing plain old javascript away to a dark corner where I don’t have to look at it, and can instead focus on the positives of javascript (the same could be said for prototype, dojo, etc).
Until today, jQuery has performed admirably in this role, and has a fantastic selection/manipulation to boot. Until today.
You see, there’s this weird event called ‘beforeunload’, which triggers right as a user is navigating away from a page, but before they actually leave the page. The sole purpose of this event is to confirm with the user that they want to leave, that they might lose unsaved changes, etc. It’s not exactly a standard event: some browsers support it, some don’t, and the implementations can be subtly different. So, naive me, I thought this would be a great place to use jQuery, and abstract away all that cross-browser pain that has bitten me so many times before.
No can do. Craig Stuntz and I got into a brief discussion today on Twitter, and along with some googling and a quick spike that I did, I learned that jQuery has no truck with onbeforeunload, and if you want to use it, you’re stuck with plain old javascript and cross-browser pain. Booo. Fortunately, rare is the occasion where you should use this non-standard event (if ever).
How about a followup blog post wrapping up your cross-browser beforeunload event handling into a jQuery plugin?
Don’t make me do stuff
Actually, it was another developer who did all the heavy lifting with the cross-browser stuff while I complained about it, but I’ll see if I can get the code posted.
A user tries to leave a site and you blast them with an ad. You close that ad and it spawns another one. Does jQuery really need to make it easier to sell anti-spyware software?
Ah, well that would be the "unload" event, and jQuery already makes that quite easy. The "beforeunload" event isn’t actually a normal event as such: it only shows a "OK/Cancel" box with the text of your choice.
I gotcha. You don’t want users accidentally leaving a page before they submit their form. I’d call that a user education issue and be done with it.
Yeah, I think I mostly agree with that. Not to mention it affords no such protection to users with JavaScript off, mobile users, etc. Customers can be very insistent though.