Skip to content

Instantly share code, notes, and snippets.

@maccman
Created July 22, 2013 20:40
Show Gist options
  • Save maccman/6057476 to your computer and use it in GitHub Desktop.
Save maccman/6057476 to your computer and use it in GitHub Desktop.
$ = jQuery
$.fn.lineHeight or= ->
if height = @data('lineHeight')
return height
# Create a hidden div with the same font
# properties, then measure its height
$shadow = $('<span />')
$shadow.css({
position: 'absolute',
top: -10000,
left: -10000,
fontSize: @css('fontSize'),
fontFamily: @css('fontFamily'),
lineHeight: @css('lineHeight')
})
$shadow.text('lineHeight')
$shadow.appendTo('body')
height = $shadow.outerHeight()
@data(lineHeight: height)
$shadow.remove()
height
autoExpand = ->
$el = $(this)
lines = $el.val().split('\n').length
lineHeight = $el.lineHeight() or 1
minHeight = lines * lineHeight
# Return if min-height is already more
# than whatever we want to set
if original = $el.css('minHeight')
original = parseInt(original, 10)
return if (original - 10) > minHeight
minHeight += 40
$el.css(
transition: 'min-height 100ms ease-out',
minHeight: minHeight
)
$(document).on(
'keyup',
'textarea[autoexpand]',
autoExpand
)
@syropian
Copy link

By the looks of it, this only expands upon actually pressing the return key, and not when the text wraps to a new line correct?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment