Skip to content

Instantly share code, notes, and snippets.

@niorad
Created February 15, 2018 14:20
Show Gist options
  • Save niorad/0d6f7aa92a47c965cb0fb06b8ad731bb to your computer and use it in GitHub Desktop.
Save niorad/0d6f7aa92a47c965cb0fb06b8ad731bb to your computer and use it in GitHub Desktop.
Changing Forms with Browser History push/pop
<html>
<head>
<title>Browser-History Push/Pop</title>
</head>
<body>
<form id="myform">
<label>
<input type="checkbox" name="cb1">CB1</label>
<br>
<label>
<input type="checkbox" name="cb2">CB2</label>
<br>
<label>
<input type="checkbox" name="cb3" checked>CB3</label>
<br>
<label>
<input type="checkbox" name="cb4">CB4</label>
<br>
<label>
<input type="checkbox" name="cb5">CB5</label>
</form>
<script>
var myForm = document.getElementById('myform');
function formElements() {
return [].slice.call(myForm.elements);
}
function formToStateObject(formNode) {
return formElements().reduce(function (acc, item) {
if (item.type !== 'checkbox') return acc;
if (!item.checked) return acc;
acc[item.name] = item.checked;
return acc;
}, {})
}
function stateObjectToForm(stateObject, formNode) {
uncheckForm(formNode);
for (var property in stateObject) {
if (stateObject.hasOwnProperty(property)) {
formNode.querySelector('[name=' + property + ']').checked = true;
}
}
}
function pushFormState(formNode) {
history.pushState(formToStateObject(formNode), '', '');
}
function uncheckForm(formNode) {
formElements().forEach(function (e) {
e.checked = false;
})
}
window.onpopstate = function (event) {
console.log(history.state);
stateObjectToForm(history.state, myForm);
}
formElements().forEach(function (el) {
el.addEventListener('change', function (e) {
pushFormState(myForm);
});
});
history.replaceState(formToStateObject(myForm), '', '');
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment