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
eventListenerto track when a user starts typing into a form/textarea; - When that fires, set off a new
eventListenerto 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
localStorageagainst akeyfor 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 thelocalStoragekey; - Now, with that setup, you can add some initial logic that checks
localStorageon page load for a key that matches the current URL and, if found, parse the JSON and populate the form.
Et voila! Neat π