How can I put a <span> inside of an <input>?
Wrap both your input and your span inside a container, position this container as relative, and the span as absolute. You can now do whatever you like with the span.
function checkInput(text) {
if (text) {
$("#clearBtn1").addClass("show");
} else {
$("#clearBtn1").removeClass("show");
}
}
.text-container {
display: inline-block;
position: relative;
overflow: hidden;
}
.clearBtn {
position: absolute;
top: 0;
right: -15px;
transition: right 0.2s;
}
.show {
right: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text-container">
<input type="text" onkeyup="checkInput(this.value)" />
<span id="clearBtn1" class="clearBtn">X</span>
</div>
Hide the X by default and use the show class when needed
.clearBtn {
position: relative;
left: 0;
transition: left 0.3s;
display: none;
}
.show {
display: inline;
}
JS
function checkInput(text) {
if (text != ""){
$("#clearBtn1").addClass("show");
} else {
$("#clearBtn1").removeClass("show");
}
}
http://jsfiddle.net/qgy8Ly5L/18/
Check out this updated fiddle:
function checkInput(text) {
if (text) {
$("#clearBtn1").addClass("show");
} else {
$("#clearBtn1").removeClass("show");
}
}
.clearBtn {
position: relative;
left: 0;
transition: left 0.3s;
visibility: hidden;
}
.show {
left: -18px;
visibility: visible;
}
http://jsfiddle.net/qgy8Ly5L/19/
By using visibility
you get to keep the element in the DOM. This will keep things smooth when it reappears. Notice the use of a "truthy" if statement.