Auto Expand Mixin

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.

Syntax

autoExpand(selectorList, direction)

Example

Input:

autoExpand('textarea', 'height')

Output:

/* textarea { height: auto-expand; } */

Code

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'

}

Techniques Capable