Search code examples
htmlfont-awesomeplaceholder

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>"

Solution

  • 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="&#xF002;"/>
      </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.