Skip to content

Instantly share code, notes, and snippets.

@grace-snow
Last active October 8, 2020 12:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grace-snow/ab0ca1698ec8c975af6a2493694554f1 to your computer and use it in GitHub Desktop.
Save grace-snow/ab0ca1698ec8c975af6a2493694554f1 to your computer and use it in GitHub Desktop.
A callback function to make text/number inputs resizable to their content. Remember, ch units are the width of 0 in a font, so this is not entirely accurate for small characters like decimal points or the number `1`.
/**************************************
* Make any inputs resizable to their content
*/
function resizeInput() {
this.style.width = this.value.length + "ch";
this.style.minWidth = "1ch";
}
function makeInputsResizeble(){
var resizableInputs = document.querySelectorAll('.js-input-resize'); // get all resizable inputs (nodelist)
for (var i = 0, length = resizableInputs.length; i < length; i++) {
var item = resizableInputs[i]; // get individual inputs
item.addEventListener('input', resizeInput); // bind the "resizeInput" callback on "input" event
item.addEventListener('focusout', resizeInput);
resizeInput.call(item);
}
}
makeInputsResizeble();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment