I am just testing how I solved simple stuff.
Goal: The aim is to expand the width of an input
and collapse it.
When mouseover
expand,.
When mouseout
collapse.
When you have text inside the input
keep it expanded.
To me it seems too much, repeating some stuff in JS. Also thought about adding a debouncer or throttle but was not successful.
There's probably another way to solve it with pure CSS.
HTML:
<body>
<p>
2 inputs, 1 is collapsed
the other is expanded
</p>
<br>
collapsed
<br>
<input type="text" class="collapsed">
<br>
<br>
expanded
<br>
<input type="text" class="expanded">
</body>
CSS:
input {
width: 20px;
transition: width 1s;
}
.expanded{
width: 256px;
}
JS:
let collapsedInput = document.querySelector('.collapsed');
const handleMouseOut = () => {
collapsedInput.classList.remove('expanded');
}
const handleMouseOVer = () => {
collapsedInput.classList.add('expanded');
}
collapsedInput.addEventListener('mouseover', handleMouseOVer);
collapsedInput.addEventListener('mouseout', handleMouseOut);
collapsedInput.addEventListener('input', () => {
if(collapsedInput.value !== ""){
collapsedInput.classList.add('expanded');
collapsedInput.removeEventListener('mouseout', handleMouseOut);
} else {
collapsedInput.classList.remove('expanded');
collapsedInput.addEventListener('mouseout', handleMouseOut);
}
})