Last active
June 13, 2018 17:15
-
-
Save nfreear/2b49fb478af412730e3cd79ef56523cd to your computer and use it in GitHub Desktop.
Autosave form data to localStorage, using HTML IDs as the key
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> <html lang="en"> <title> *autosave </title> | |
<h1> autosave </h1> | |
<p><label> Field 1 <input id="uniq_id_1" class="autosave" ></label> | |
<p><label> Field 2 <input class="autosave" ></label> | |
<p><label> Field 3 <select class="autosave" ><option>Option A</option><option>Option B</option></select> | |
<p><label> Field 4 <textarea class="autosave" ></textarea></label> | |
<script src="https://unpkg.com/jquery@^3/dist/jquery.slim.min.js"></script> | |
<script id="auto-id-js"> | |
(function (W, $, prefix) { | |
$('.autosave').each(function (idx, el) { | |
$(this).attr({ id: prefix + idx }); | |
}); | |
})(window, window.jQuery, 'uniq_id_'); | |
</script> | |
<script data-autosave='{ "_debug": true }'> | |
(function (W, path, storage, $, q) { | |
var defaults = { | |
selector: '.autosave[ id ]', | |
interval: 2000, | |
debug: false, | |
log: function () {} | |
}; | |
var options = JSON.parse($('script[ data-autosave ]').attr('data-autosave') || {}); | |
var CFG = $.extend(defaults, options); | |
if (CFG.debug) { | |
CFG.log = console.warn; | |
} | |
CFG.log('autosave, CFG:', CFG, $.fn.jquery); | |
var $fields = $(CFG.selector); | |
CFG.log('autosave, fields:', $fields); | |
setDate(); | |
restore(); | |
start(); | |
function setDate() { | |
var hash = btoa(path).substr(0, 10); | |
storage.setItem(CFG.selector + ':' + path + '#' + hash + '-date', new Date()); | |
} | |
function restore () { | |
$fields.each(function (idx, el) { | |
var value = storage.getItem(key(el)); | |
if (value) { | |
$(el).val(value); | |
CFG.log('autosave, restore', key(el), value); | |
} | |
}); | |
} | |
var timer; | |
function start() { | |
timer = W.setInterval(function () { | |
$fields.each(function (idx, el) { | |
if ($(el).val()) { | |
storage.setItem(key(el), $(el).val()); | |
CFG.log('autosave, save', $(el)); | |
} | |
}); | |
CFG.log('autosave, ping'); | |
}, CFG.interval); | |
CFG.log('autosave, start'); | |
} | |
function key(elem) { | |
return CFG.selector + ':' + path + '#' + $(elem)[ 0 ].id; | |
} | |
})(window, window.location.pathname, window.localStorage, window.jQuery, document.querySelectorAll); | |
</script> | |
<pre> | |
© Nick Freear, 13-june-2018 | https://gist.github.com/nfreear/2b49fb478af412730e3cd79ef56523cd | |
* https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage | |
* https://npmjs.com/package/input-autosave | |
* https://gist.github.com/gcmurphy/3651776 | |
</pre> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment