<form id="chat" method="post" action="/my-backend-script">
<input type="text" placeholder="What's on your mind?" />
<input type="submit" value="Post" />
</form>
#chat {
display: flex;
}
#chat input[type="text"],
#chat input[type="submit"] {
padding: 5px 10px;
border: 1px solid #666;
outline: none;
}
#chat input[type="text"] {
flex: 1;
margin-right: 10px;
}
#chat input[type="text"]:focus {
border-color: #369;
}
#chat input[type="submit"] {
margin-right: 10px;
text-transform: uppercase;
}
#chat input[type="submit"]:active {
border-color: #369;
background-color: #369;
color: #fff;
}
/*
Let's break down this app in small and
simple functions, then bring them all
together to write an easy to read
logical piece of code
*/
const getChat = () =>
document
.getElementById('chat')
const getChatInput = () =>
document
.querySelector('#chat input[type="text"]')
const getChatMessage = () =>
getChatInput().value
const resetChatInput = () => {
const input = getChatInput()
input.value = ''
input.focus()
}
/*
The following 4 functions are
"PURE FUNCTIONS"
What does that mean?
Why are "pure functions" important?
*/
const messageIsValid = text =>
text.length > 0
const sendMessage = text =>
alert(`Send: ${text}`)
const showError = () =>
alert('Please type the message you want to sent')
const cancelEvent = (event) => {
event.preventDefault()
event.stopPropagation()
}
/*
Finally, we can write the event handler
as a simple list of smaller functions
*/
const onFormSubmit = (event) => {
cancelEvent(event)
const message = getChatMessage()
// the ternary conditional operator
// works exceptionally well with
// custom functions names.
//
// when you choose good names,
// you can almost read your code as
// it was plain english.
//
// it makes it dramatically easy to
// spot logical mistakes
messageIsValid(message)
? sendMessage(message)
: showError()
resetChatInput()
}
getChat().addEventListener('submit', onFormSubmit)
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.