Use Font Awesome Icon in Placeholder
Is it possible to use Font Awesome Icon in a Placeholder? I read that HTML isn't allowed in a placeholder. Is there a workaround?
placeholder="<i class='icon-search'></i>"
If you're using FontAwesome 4.7
this should be enough:
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<input type="text" placeholder=" Search" style="font-family:Arial, FontAwesome" />
A list of hex codes can be found in the Font Awesome cheatsheet. However, in the lastest FontAwesome 5.0 this method does not work (even if you use the CSS approach combined with the updated font-family
).
You can't add an icon and text because you can't apply a different font to part of a placeholder, however, if you are satisfied with just an icon then it can work. The FontAwesome icons are just characters with a custom font (you can look at the FontAwesome Cheatsheet for the escaped Unicode character in the content
rule. In the less source code it's found in variables.less The challenge would be to swap the fonts when the input is not empty. Combine it with jQuery like this.
<form role="form">
<div class="form-group">
<input type="text" class="form-control empty" id="iconified" placeholder=""/>
</div>
</form>
With this CSS:
input.empty {
font-family: FontAwesome;
font-style: normal;
font-weight: normal;
text-decoration: inherit;
}
And this (simple) jQuery
$('#iconified').on('keyup', function() {
var input = $(this);
if(input.val().length === 0) {
input.addClass('empty');
} else {
input.removeClass('empty');
}
});
The transition between fonts will not be smooth, however.
I solved with this method:
In the CSS I used this code for the fontAwesome class:
.fontAwesome {
font-family: 'Helvetica', FontAwesome, sans-serif;
}
In the HTML I have added the fontawesome class and the fontawesome icon code inside the placeholder:
<input type="text" class="fontAwesome" name="emailAddress" placeholder=" insert email address ..." value="">
You can see in CodePen.