Skip to content

Instantly share code, notes, and snippets.

@davidbgk
Forked from adactio/saveTextarea.js
Created October 14, 2020 13:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidbgk/6975bf150ae53bb35ec6764979d2b543 to your computer and use it in GitHub Desktop.
Save davidbgk/6975bf150ae53bb35ec6764979d2b543 to your computer and use it in GitHub Desktop.
Put the contents of a textarea into localStorage if the user leaves the page before submitting the form.
// Licensed under a CC0 1.0 Universal (CC0 1.0) Public Domain Dedication
// http://creativecommons.org/publicdomain/zero/1.0/
(function (win, doc) {
// Cut the mustard.
if (!win.localStorage) return;
// You should probably use a more specific selector than this.
var textarea = doc.querySelector('textarea');
// The key for the key/value pair in localStorage is the current URL.
var key = win.location.href;
var item = null;
// Use the 'pagehide' event in modern browsers or 'beforeunload' in older browsers.
var unloadEvent;
if ('onpagehide' in win) {
unloadEvent = 'pagehide';
} else {
unloadEvent = 'beforeunload';
}
// If there's a localStorage entry for the current URL, update the textarea with the saved value.
item = win.localStorage.getItem(key);
if (item) {
var data = JSON.parse(item);
textarea.value = data.content;
}
// This function will store the current value of the textarea in localStorage (or delete it if the textarea is blank).
function updateStorage() {
if (textarea.value) {
item = JSON.stringify({'content': textarea.value});
win.localStorage.setItem(key, item);
} else {
win.localStorage.removeItem(key);
}
// This event listener is no longer needed now so remove it.
win.removeEventListener(unloadEvent, updateStorage);
}
// When the user presses a key just *once* inside the textarea, run the storage function when the page is unloaded.
textarea.addEventListener('keyup', function() {
win.addEventListener(unloadEvent, updateStorage);
}, {'once': true});
// When the form is submitted, delete the localStorage key/value pair.
textarea.form.addEventListener('submit', function() {
win.localStorage.removeItem(key);
win.removeEventListener(unloadEvent, updateStorage);
});
}(this, this.document));
@davidbgk
Copy link
Author

Related blog entry: https://adactio.com/journal/17516

(one day, Github will allow to fork comments too :) )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment