JSFiddle - React, Tailwind, and code Playground
by Ian Hazzard
HTML
<div class="text-container">
<input type="text" id="input1" onkeyup="checkInput(this.value)" onblur="checkInput()" onfocus="checkInput(this.value)"/> <span id="clearBtn1" class="clearBtn" onclick="clearInput()">✕</span>
</div>
CSS
#clearBtn1 {
cursor: pointer;
}
.text-container {
display: inline-block;
position: relative;
overflow: hidden;
}
.clearBtn {
position: absolute;
top: 0;
bottom: 0;
height: 100%;
right: -10px;
opacity: 0;
margin: auto;
transition: all 0.3s;
}
.show {
right: 5px;
opacity: 1;
}
JavaScript
function checkInput(text) {
if (text != null && text != "") {
$("#clearBtn1").addClass("show");
} else if (text == null || text == "") {
$("#clearBtn1").removeClass("show");
}
}
function clearInput() {
$("#input1").val('');
$("#clearBtn1").removeClass("show");
$("#input1").focus();
}