Simple input class change with vanilla JS 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:

&lt;body&gt;
&lt;p&gt;
    2 inputs, 1 is collapsed 
    the other is expanded

&lt;/p&gt;    
&lt;br&gt;
collapsed   
&lt;br&gt;
    &lt;input type="text" class="collapsed"&gt;
    &lt;br&gt;
    &lt;br&gt;
    expanded
    &lt;br&gt;
    &lt;input type="text" class="expanded"&gt;
&lt;/body&gt;


CSS:

input {
    width: 20px;
    transition: width 1s;
}

.expanded{
    width: 256px;
}


JS: 

let collapsedInput = document.querySelector('.collapsed');

const handleMouseOut = () =&gt; {
    collapsedInput.classList.remove('expanded');
}

const handleMouseOVer = () =&gt; {
    collapsedInput.classList.add('expanded');
}

collapsedInput.addEventListener('mouseover', handleMouseOVer);

collapsedInput.addEventListener('mouseout', handleMouseOut);

collapsedInput.addEventListener('input', () =&gt; {
    if(collapsedInput.value !== ""){
        collapsedInput.classList.add('expanded');
        collapsedInput.removeEventListener('mouseout', handleMouseOut);
    } else {
        collapsedInput.classList.remove('expanded');
        collapsedInput.addEventListener('mouseout', handleMouseOut);
    }
})
Review

The biggest critique about the Javascript I have is that collapsedInput could be declared with const because it doesn't get re-assigned.

It is possible that the code in the event listener for the input event could be simplified using classList.toggle().

If there is only one element with class name collapsed then perhaps it would be better to use an id attribute and use document.getElementById() to select it. Those older methods are faster than the querySelector() varieties. 

Dramatic simplification

The question contained this text:


  There's probably another way to solve it with pure CSS.


That is correct. One way is to use the required attribute on the first &lt;input&gt; element along with the :valid and :hover pseudo-selectors :



input {
    width: 20px;
    transition: width 1s;
}

input:valid,
input:hover,
.expanded {
    width: 256px;
}
&lt;p&gt;
    2 inputs, 1 is collapsed 
    the other is expanded

&lt;/p&gt;    
&lt;br&gt;
collapsed   
&lt;br&gt;
    &lt;input type="text" class="collapsed" required&gt;
    &lt;br&gt;
    &lt;br&gt;
    expanded
    &lt;br&gt;
    &lt;input type="text" class="expanded"&gt;




Perhaps someday the CSS pseudo-class :blank will be supported by some browsers... If that is the case, then the required attribute wouldn't be needed.