Skip to content

Instantly share code, notes, and snippets.

@iamdustan
Created November 21, 2018 17:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamdustan/67889711eef84a7314ba62d9f6c2becc to your computer and use it in GitHub Desktop.
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.
<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>
@zeshhaan
Copy link

zeshhaan commented Aug 3, 2020

Hey!
Can we add this to our Webflow sites?

@iamdustan
Copy link
Author

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.

@zeshhaan
Copy link

zeshhaan commented Aug 3, 2020

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