[CSS] Transform a button to a text input
Here is a cool CSS trick I found for actions that require a text value:
See the code in action on CodePen
HTML
<form id='buttonWithText' onSubmit={this.onSubmit}>
<div id='slider' class='collapsed'>
<input type='button' id='toggle' value='Change username'>
<input type='text' id='input' tabindex='-1' placeholder='username' size=10>
<input type='submit' id='ok' tabindex='-1' value='ok'>
</div>
</form>
CSS
#buttonWithText {
overflow: hidden;
width: 200px;
}
#slider {
display: flex;
width: 200%;
transition: 0.5s;
}
#slider.expanded {
transform: translateX(-50%);
}
#toggle {
flex: 0 0 50%;
}
#input {
flex: auto;
}
#ok {
flex: none;
}
JavaScript
function expand() {
slider.className = 'expanded';
setTimeout(function() {
input.focus();
}, 500);
}
function collapse() {
slider.className = 'collapsed';
input.blur();
}
toggle.onclick = expand;
input.onblur = function() {
setTimeout(collapse, 100);
}
buttonWithText.onsubmit = function(e) {
e.preventDefault();
alert("New username: " + input.value);
collapse();
}