Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Font awesome icon font as a placeholder in input after adding class with jquery

I am trying to use font-awesome icons as a placeholder in search input field.

Jsfiddle examples

I use corresponding html entity as a placeholder, then use pseudo class to style placeholder with correct font-family (example 2 in jsfiddle):

HTML:

<div class="wrapper">
    <input class="icon" type="text" placeholder="&#61442;" />
</div>

CSS:

.wrapper {
    font-family:'arial', sans-serif;
}
input.icon {
    padding:5px;
}
input.icon::-webkit-input-placeholder {
    font-family:'FontAwesome';
}
input.icon::-moz-placeholder {
    font-family:'FontAwesome';
}
input.icon::-ms-input-placeholder {
    font-family:'FontAwesome';
}

It works as expected.

The problem starts when I try to add input class and placeholder via jquery (example 1 in jsfiddle):

JS:

$(document).ready(function() {
$('.wrapper input:first').addClass('icon');
$('.wrapper input:first').attr("placeholder", "&#61442;");
});

It doesn't apply font-family to input placeholder and just shows entity text instead.

I tried to mix things around and finally giving up. Please help!

Jsfiddle examples

P.S.: The rout of adding :before with font content to input wrapper in css will not work for my particular case.

like image 225
Acidon Avatar asked Mar 14 '23 14:03

Acidon


2 Answers

You should parse the hash first. You can use $.parseHTML:

$('.wrapper input:first').attr("placeholder", $.parseHTML("&#61442;")[0].data);
like image 77
Filipe Avatar answered Apr 25 '23 15:04

Filipe


You can try something like this:

$('.wrapper input:first').attr("placeholder", $('<textarea />').html("&#61442;").html());

JSFiddle

This works by passing the value as HTML instead of text, which can be achieved by creating a reference to an element which doesn't really exist.

like image 38
Daniel Waghorn Avatar answered Apr 25 '23 16:04

Daniel Waghorn