JSFiddle - React, Tailwind, and code Playground
by shapeshifta
HTML
<form>
<input class="js-clearable clearable" type="text" name="" value="" placeholder="Enter a Search term" />
</form>
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 {
display:none;
}
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 ($) {
// Create the defaults once
var pluginName = 'clearableInputs',
defaults = {
clearableClass: '.js-clearable',
clickArea: 'x'
};
// The actual ClearableInputs constructor
function ClearableInputs(element, options) {
this.element = element;
this.options = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
ClearableInputs.prototype = {
init: function () {
var that = this,
element = that.element,
options = that.options;
$(element)
.on('input propertychange keydown', options.clearableClass, function () {
//add x on input
$(this)[that.toggleClass(this.value.length)](options.clickArea);
})
.on('mousemove', '.' + options.clickArea, function (e) {
//detect if mouse is on x (background)
var $this = $(this),
visibleArea = this.offsetWidth - parseInt($this.css('padding-right'), 10),
mouseArea = e.clientX - this.getBoundingClientRect().left,
value = visibleArea < mouseArea;
$this[that.toggleClass(value)]('onX');
})
.on('click', '.onX', function () {
//detect click on x
$(this).removeClass(options.clickArea + ' onX').val('');
});
},
...