eroock
Since: Sep, 2012
#2: Sep 3rd 2015 at 1:31:30 PM
Rule #1: Don't do large and complex edits in the edit window. I use an external text editor with a save function.
Total posts: 2

(I looked for an existing conversation with this topic, but couldn't find one. Both the search interface and the wishlist forum pagination seemed kind of wonky, though, so I may have missed something. If so, sorry about that.)
Thanks to a clash between editor and browser keyboard shortcuts, I've accidentally thrown away edits more often than I'd like. I wrote a user script to stop me doing this, and it occurred to me that I'm probably not the only one with the problem, so I thought I'd mention it in case someone empowered to do so thinks the functionality's worth adding to the site code proper.
The script I wrote is on [[Tropers/Ham-peas my user page]]. I see TV Tropes uses jQuery, which I didn't, but it should be pretty easy to port, and should also work OK without being ported since pretty much all the browsers now support
.querySelector().Technical discussion:
The save button gets a click handler that sets a flag, which in turn cancels the warning. (Saved edits aren't being thrown away, so there's no need to warn about that.) The "cancel edit" button doesn't get a similar handler, because I figure there's a reasonable use case for confirming that action.
Keying the warning off the "keydown" event on the textarea is less than wholly ideal, because it'll trigger even if no actual changes were made to the content. For example, if you click into the textarea and just hit the Shift key once, it'll fire the event and set up the warning.
The "change" event seems more natural, but it only fires when the element loses focus, so you'd have to remember to click or tab away from the edit box before you accidentally throw your edits away. That's not really a solution.
The really sensible behavior would be to take what I've done and extend it with a hash comparison to see whether the content of the edit box actually differs from what it was at page load; if nothing has actually changed, don't present the warning. I didn't include that because it'd require an MD 5 library or similar and is overkill for my personal use case, but I'd want to do that or something like it in a serious implementation.
Speaking of things I'd want to do in a serious implementation, there's no real need to have the keydown handler fire more than once, since all it does is install a couple of event listeners. The function body is wrapped in a conditional to stop it actually installing those handlers multiple times, but a serious implementation would have it install its event listeners and then uninstall itself, which would be trivial to do by naming the function bound to beforeunload and having it call window.removeEventListener('beforeunload') with its own name as the second argument.