JSFiddle - React, Tailwind, and code Playground
HTML
<input class="clearable" type="text" name="" value="" placeholder="Enter a Search term" />
CSS
.clearable {
background:url(http://i.imgur.com/z7ZSYjt.png) no-repeat right -10px center;
border:1px solid #999;
padding:3px 18px 3px 4px;
/* same right-padding like offset */
border-radius:3px;
transition: background 0.4s;
}
.clearable.x {
background-position: right 5px center;
}
.clearable.onX {
cursor:pointer;
}
input[type=text]::-ms-clear {
margin-right:20px
}
JavaScript
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module depending on jQuery.
define(['jquery'], function (jQuery) {
return factory(jQuery);
});
} else {
// No AMD. Register plugin with global jQuery object.
factory(jQuery);
}
}(function ($) {
//add or remove class
function toggle(v) {
return v ? 'addClass' : 'removeClass';
}
$(document)
.on('input propertychange', '.clearable', function () {
//add x on input
$(this)[toggle(this.value.length)]('x');
})
.on('mousemove', '.x', function (e) {
//detect if mouse is on x (background)
var value = this.offsetWidth - parseInt($(this).css('padding-right'), 10) < e.clientX - this.getBoundingClientRect().left;
$(this)[toggle(value)]('onX');
})
.on('click', '.onX', function () {
//detect click on x
$(this).removeClass('x onX').val('');
});
}));