Created
November 21, 2018 17:24
-
-
Save iamdustan/67889711eef84a7314ba62d9f6c2becc to your computer and use it in GitHub Desktop.
Automatically saves and restores form data on a page. Written for Webflow.com custom code integration.
This file contains hidden or 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
<script> | |
(() => { | |
const debounce = (fn) => { | |
let timeout; | |
let arg; | |
const later = () => { | |
timeout = null; | |
fn(arg); | |
arg = null; | |
}; | |
return (_arg) => { | |
arg = _arg; | |
clearTimeout(timeout); | |
timeout = setTimeout(later, 300); | |
}; | |
}; | |
const save = debounce((event) => { | |
const form = event.target.form; | |
localStorage.setItem( | |
`form-${form.name}`, | |
JSON.stringify([...new FormData(form)]) | |
); | |
}); | |
const clear = (event) => { | |
localStorage.removeItem(`form-${event.target.name}`); | |
}; | |
const restore = () => { | |
[...document.querySelectorAll('form')].forEach(form => { | |
const formStorage = localStorage.getItem(`form-${form.name}`) | |
if (!formStorage) { | |
return; | |
} | |
try { | |
const data = JSON.parse(formStorage); | |
data.forEach(([key, val]) => { | |
if (val) { | |
form.querySelector(`[name="${key}"]`).value = val; | |
} | |
}); | |
} catch(err) { | |
console.error(err); | |
} | |
}); | |
}; | |
document.addEventListener('change', save); | |
document.addEventListener('submit', clear); | |
document.addEventListener('DOMContentLoaded', restore); | |
})(); | |
</script> |
Yup! Feel free to copy-paste it in. It should be pretty safe, but as with all custom code, no guarantees provided :D
oh, I’m using some ES6 features that require modern-ish browsers so if you support a bunch of versions of IE, for example, you’ll need to make some minor modifications.
Thanks mate. This worked flawlessly🥳 Though I have to change the checkbox from custom to default.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey!
Can we add this to our Webflow sites?