What we're building
If you've ever used google keep you must be familiar with their dynamic input form for creating a note. The form looks simple on first look, but it can be a bit tricky to come up with a solution.
The end result is going to look like this.
If you directly want to dive into the code, you can check out the codepen here.
The Markup
Let's work on our form markup i.e html and css. I am just going to create a simple form with two input tags. This part is completely optional, if you're a beginner you may find some new things but if you're not you can skip to the next section.
<form action="">
<input type="text" placeholder="Title" id="title" />
<input type="text" placeholder="Take a note..." id="content" />
</form>
Since I am creating this form in codepen, you may see some CSS on the body, the CSS in body just centers the form, and you may skip over it.
Styling our form
form {
display: flex;
flex-flow: column;
width: 540px;
border-radius: 8px;
border: solid 1px #5f6368;
box-shadow: 0 3px 5px rgba(0, 0, 0, 0.5);
}
To stack the input I've used display: flex
with column direction.
The Script
Now let's add some interactivity on our form using JavaScript. In google keep's input the title input is shown after the input that contains the content for our note is focused, we're going to implement the same.
First I am going to get the elements in our html inside javascript.
const form = document.querySelector('form');
const title = document.getElementById('title');
const content = document.getElementById('content');
When a user first looks at the form, we don't want to show the title input, to do that, we're going to set the display property to none.
title.style.display = 'none';
After the user focuses on content input we want to show the title input.
content.addEventListener('focus', () => title.style.display = '');
Now we can show the title input when the content input is focused, but we should also be able to hide the title when the user is not focused on both of the inputs, let's work on that.
I am going to capture focusout
event in the form.
form.addEventListener('focusOut', handleFocusOut);
Now you may wonder why focusout
on form instead of blur
event on inputs?
By listening on focusout
event we get access to relatedTarget
property, which is useful since we want to know if the user has clicked on an input inside the form or the user has clicked outside the form.
Now let's define the callback function we passed i.e handleFocusOut
.
function handleFocusOut(event) {
let relatedTarget = event.relatedTarget;
if(relatedTarget) {
return;
}
title.style.display = 'none';
}
Wrap up
Our google keep style form is complete, if you want to look at the code the you can checkout the codepen here.
Feel free to add suggestions using the comment section.
Top comments (0)