JSFiddle - React, Tailwind, and code Playground
HTML
<span class='clearIcon'>
<input type='text' name='asd' class='searchInput' />
</span>
CSS
.clearIcon {
position: relative;
}
.keypress {
position: absolute;
width: 20px;
height: 20px;
background-color: #333;
}
JavaScript
// Don't focusout if the ".keypress" is clicked
$(".searchInput").focusout(function(e) {
$(".keypress").css('opacity', '0');
if(e.currentTarget != this) {
if ($(".keypress").length > 0) {
$(".keypress").remove();
}
}
})
$(".searchInput").focus(function() {
if ($(".searchInput").val() != "") {
DisplayClearIcon(this);
}
})
$(".searchInput").keyup(function() {
if($(this).val() != "") {
DisplayClearIcon(this);
} else {
$(".keypress").remove();
}
})
function DisplayClearIcon(elem) {
$("<span class='keypress'><i class='icon-remove-sign'></i></span>").appendTo($(elem).parent());
$(".keypress").click(function(e) {
event.preventDefault();
$(elem).val("");
$(".keypress").hide();
})
}