Skip to content

Instantly share code, notes, and snippets.

@rjungemann
Created July 18, 2011 18:54
Show Gist options
  • Save rjungemann/1090320 to your computer and use it in GitHub Desktop.
Save rjungemann/1090320 to your computer and use it in GitHub Desktop.
Auto-Resizing Text Area
# Auto-Resizing Text Area
# Works in Chrome, Firefox, and IE7+
# notes:
# * 'rows' and 'cols' attributes should be set on the textarea
# * 'rows' becomes the minimum number of rows
# * 'overflow' should be set to 'hidden' and 'height' should be set to 'auto'
# sass:
# textarea
# overflow: hidden
# height: auto
#
# haml:
# %textarea{ :rows => 5, :cols => 40 }
#
# coffee:
# $('textarea').autoResize()
$.fn.autoResize = ->
@each ->
cols = @cols
rows = @rows
grow = ->
linesCount = 0
lines = @value.split '\n'
i = lines.length - 1
while i >= 0
linesCount += Math.floor ( lines[i].length / cols ) + 1
--i
if linesCount >= rows then @rows = linesCount + 1 else @rows = rows
$(this).bind keydown: grow, keyup: grow
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment