A very clever (and well explained) method for helping users complete forms. Particularly with modern pop-up forms, I'd say at least once a month I'm part way through typing something and accidentally shift my mouse somewhere that causes the form to close, losing everything I had written 😡 Jeremy's trick of storing the current form (well, textarea
, but it should be easy to expand) content in localStorage
is a great enhancement that would solve those frustrations. Here's the gist (see what I need 😄):
- Use an
eventListener
to track when a user starts typing into a form/textarea; - When that fires, set off a new
eventListener
to track the browser's unload event usingbeforeUnload
(Jeremy explains why that method well); - If that second listener fires, save the content of the form into
localStorage
against akey
for the page URL/slug (you can use JSON to store multiple values in one key/value pair); - If the form is submitted without issue or firing the
eventListener
, clear thelocalStorage
key; - Now, with that setup, you can add some initial logic that checks
localStorage
on page load for a key that matches the current URL and, if found, parse the JSON and populate the form.
Et voila! Neat 👍