It’s often nice to add small font awesome icons inside form fields. For instance, on a contact form, we can add a little email icon, person icon, phone icon all inside the form field. If we include the FontAwesome Library I am a firm believer that we should get some real value out of it and not just use it for some social media icons. This is a nice little enhancement that works with the latest version of Font Awesome.
What we are making :
We will be looking at moving the icons from the left to the right-hand side, and also set up an event listener so that we can use this as a search field. For the above style, we are loading the standard icon to the left of the input, then with CSS moving it into the correct position. We then add small padding to the input to allow for the icon. This is a good place to note that FontAwesome has a cheat sheet to easily find icons, replace the fa-address-card class below with fa-icon-name from the cheat sheet. Here is the HTML code :
<i class="fa fa-address-card iconnameleft"></i>
<input class="inputleft" type="text" placeholder="Name" />
And the CSS code looks like this :
.inputleft {
padding-left:35px;
height: 2em;
width: 30em;
border: 2px solid #acacac;
border-radius: 0.5em;
font-size: 1em;
}
.iconnameleft {
position: relative;
font-size: 1.3em;
z-index: 1;
left: 10px;
top: 1px;
color: #7B7B7B;
cursor:pointer;
width: 0;
}
And thats it! the nice thing is as we aren’t using the icon code in the CSS like some solutions we can use multiple inputs with the same CSS rules and just change the icon in the HTML.
Input with FontAwesome Icon on the Right
This is what we are working on now :
The HTML code is very similar, but we now add the icon after the input :
<input class="input" type="text" placeholder="Search" />
<i class="fa fa-search iconsubmit"></i>
And the CSS code uses a negative number to align the icon back into the input :
.input {
height: 2em;
width: 30em;
border: 2px solid #acacac;
border-radius: 0.5em;
font-size: 1em;
}
.iconsubmit {
position: relative;
font-size: 1.3em;
z-index: 1;
left: -30px;
top: 1px;
color: #7B7B7B;
cursor:pointer;
width: 0;
}
So now you know how to add icons on the left and the right of an input, but what if we want the icon clickable? Well first we should make sure the user realizes its clickable, we should style a change as the user moves the cursor over the search icon, this is a simple color change but you could style it however you wanted.
.iconsubmit:hover {
color: #add8e6;
}
Now we need some JavaScript to watch this icon and do something when its clicked.
<script>
const button = document.querySelector(".iconsubmit");
button.addEventListener("click", ()=>{
// Do whatever you need here.
alert('It works!');
})
</script>
Here is all the code for both styles on a CodePen for easy reference and editing.
See the Pen Form Inputs by Matt Egginton (@matt-egginton) on CodePen.