Created
February 2, 2019 06:54
-
-
Save momin-riyadh/922c1bcacd5b4032c9ae01e34665135a to your computer and use it in GitHub Desktop.
State based UI vs. manual DOM manipulation
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
<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