Skip to content

Instantly share code, notes, and snippets.

@momin-riyadh
Created February 2, 2019 06:54
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 momin-riyadh/922c1bcacd5b4032c9ae01e34665135a to your computer and use it in GitHub Desktop.
Save momin-riyadh/922c1bcacd5b4032c9ae01e34665135a to your computer and use it in GitHub Desktop.
State based UI vs. manual DOM manipulation
<style>
body {
margin: 0 auto;
max-width: 40em;
width: 88%;
}
label,
input {
display: block;
width: 100%;
}
</style>
<form id="add-to-list">
<label for="list-item">What do you want to add to your list?</label>
<input type="text" id="list-item">
<button>Add to your list</button>
</form>
<ul id="list"></ul>
<script>
document.addEventListener('submit', function (event) {
// Make sure our #add-to-list form was the one submitted
if (!event.target.matches('#add-to-list')) return;
// Prevent default
event.preventDefault();
// Get the list item
var item = event.target.querySelector('#list-item');
if (!item || item.length < 1) return;
// Add it to the DOM
var list = document.querySelector('#list');
var li = document.createElement('li');
li.textContent = item.value;
list.appendChild(li);
// Clear the input
item.value = '';
item.focus();
}, false);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment