This JavaScript function lets you choose between auto-expanding an element’s width and height to match its scrollWidth
or scrollHeight
. Available keywords are width
, height
, and both
.
autoExpand(selectorList, direction)
selector
is a CSS selectordirection
is a string matching width
, height
, or both
Input:
autoExpand('textarea', 'height')
Output:
/* textarea { height: auto-expand; } */
function autoExpand(selector, direction) {
var tag = document.querySelectorAll(selector)
for (var i=0; i < tag.length; i++) {
if (direction == 'width' || direction == 'both') {
tag[i].style.width = ''
tag[i].style.width = tag[i].scrollWidth + 'px'
}
if (direction == 'height' || direction == 'both') {
tag[i].style.height = ''
tag[i].style.height = tag[i].scrollHeight + 'px'
}
}
return '\n/* ' + selector + ' { ' + direction +': auto-expand; } */\n'
}