Clear icon inside Input Field

by jdcast

HTML

<!DOCTYPE html>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
  <title>Demo by Roko C.B.</title>
<body>
    <h1>Clear icon inside Input field</h1>
    <input class="clearable" type="text" name="" value="" placeholder="Enter a Search term" />   
</body>

CSS

.clearable{
  background: #fff url(data:image/gif;base64,R0lGODlhBwAHAIAAAP///5KSkiH5BAAAAAAALAAAAAAHAAcAAAIMTICmsGrIXnLxuDMLADs=) no-repeat right -10px center;
  border: 1px solid #999;
  padding: 3px 18px 3px 4px;     /* Use the same right padding (18) in jQ! */
  border-radius: 3px;
  transition: background 0.4s;
}
.clearable.x  { 
    background-position: right 5px center; 
} /* (jQ) Show icon */
.clearable.onX { 
    cursor: pointer; 
} /* (jQ) hover cursor style */

JavaScript

function tog(v){return v?'addClass':'removeClass';} 

$(document).on('input', '.clearable', function() {
    $(this)[tog(this.value)]('x');
}).on('mousemove', '.x', function(e) {
    $(this)[tog(this.offsetWidth-18 < e.clientX-this.getBoundingClientRect().left)]('onX');   
}).on('click', '.onX', function(){
    $(this).removeClass('x onX').val('').change();
});