<!-- Blog post here https://codepen.io/danielwarren/post/auld-lang-refactoring -->
<div class="container">
<h1>Add Item to Array</h1>
<form id="form">
<input type="text" id="item">
<input type="submit">
</form>
<pre id="output">Ouput here...</pre>
</div>
body {
font-family: 'Roboto', sans-serif;
font-size: 16px;
}
.container {
width: 80%;
margin: 35px auto 0 auto;
}
h1 {
border-bottom: 3px solid #cc0000;
padding-bottom: 5px;
}
pre {
font-family: 'Roboto Mono', monospace;
font-size: 66%;
background: #efefef;
padding: 25px;
margin-top: 25px;
}
input[type=text] {
width: 100%;
padding: 12px 20px;
border: 3px solid #efefef;
margin: 8px 0;
box-sizing: border-box;
font-size: 16px;
}
input[type=button], input[type=submit], input[type=reset], button {
background-color: #cc0000;
border: none;
font-size: 16px;
color: white;
padding: 12px 24px;
border-radius: 0;
text-decoration: none;
margin: 4px 2px;
cursor: pointer;
}
const addItem = (item, list) => list.push(item)
const show = (list) => document.getElementById('output').innerHTML = list
const formListener = (form) => {
let list = []
form.addEventListener('submit', (e) => {
e.preventDefault()
let item = document.getElementById('item')
addItem(item.value, list)
show(list)
item.value = ''
})
}
formListener(document.getElementById('form'))
// Non-refactored code
//
// let form = document.getElementById('form')
// let list = []
// let output = document.getElementById('output')
// form.addEventListener('submit', (e) => {
// e.preventDefault()
// let item = document.getElementById('item')
// list.push(item.value)
// output.innerHTML = list
// item.value = ''
// })
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.