Clear Button for textbox
A clear button for textboxes using a simple jqery code.
HTML
<input class="clearable" type="text" name="" value="" />
<input class="clearable" type="text" name="" value="" />
<!-- Src: http://stackoverflow.com/questions/6258521/clear-icon-inside-input-text -->
CSS
.clearable{
background:url(http://i.imgur.com/z7ZSYjt.png) no-repeat right -10px center;
border:1px solid #999;
padding:3px 18px 3px 4px; /* USE the same right padding in jQ! */
border-radius:3px;
transition: background 0.4s; /*Remove this line if issues in Chrome (02.2014)*/
}
/* (jQ addClass:) if input has value: */
.clearable.x{
background-position: right 5px center;
}
/* (jQ addClass:) if mouse is over the 'x' input area*/
.clearable.onX{
cursor:pointer;
}
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('');
});