Clear icon on Input Field

by Shankar

HTML

<!-- Input code with X begins here -->
<!DOCTYPE html>
<html>
	<head>
		<link rel="stylesheet" type="text/css" href="index.css">
	</head>
	<body>
		Normal search: <input type="search">
		<p/>
		Search with mask: <input type="search" isPassword="true">
	</body>
</html>
<!-- Input code with X ends here -->


<!-- Search Input code begins here -->

<!DOCTYPE html>
<html>
	<head>
		<link rel="stylesheet" type="text/css" href="index.css"/>
		<script type="text/javascript" src="jquery-2.1.1.js"></script>
		<script type="text/javascript" src="index.js"></script>
	</head>
	<body>
		Enter something:
		<input class="clearable" type="text" name="" value="" placeholder="" />
	<body>
</html>


<!-- Search input code ends here -->

CSS

/* Input code with X begins here */

input[isPassword="true"] {
	-webkit-text-security: disc;
}

/* Input code with X ends here */

/* Search Input CSS code begins here */

.clearable{
  background: #fff url(icoX.gif) 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 */

/* Search Input CSS ends here */

JavaScript

<!-- Index.js code begins here -->
    index.js

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();
});

<!-- index.js code ends here -->