Skip to content

Instantly share code, notes, and snippets.

@Burgestrand
Created January 16, 2010 14:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Burgestrand/278830 to your computer and use it in GitHub Desktop.
Save Burgestrand/278830 to your computer and use it in GitHub Desktop.
A self-expanding textarea similar to Facebook’s implementation
<!DOCTYPE html>
<html>
<head>
<title>Self-expanding textarea</title>
</head>
<body>
<textarea id="expand" rows="8" cols="40"></textarea>
<script type="text/javascript" charset="utf-8">
var textarea = document.getElementById('expand')
var div = document.createElement('div')
if (textarea)
{
var style = function (s) { return getStyle(textarea, s) }
var clone = div.style
clone.visibility = 'hidden'
clone.position = 'relative'
clone.zIndex = '1'
// Kopiera utseendet
clone.width = style('width')
clone.fontFamily = style('font-family')
clone.fontSize = style('font-size')
clone.fontStyle = style('font-style')
clone.fontVariant = style('font-variant')
clone.lineHeight = style('line-height')
clone.wordSpacing = style('word-spacing')
clone.letterSpacing = style('letter-spacing')
// In med den
textarea.parentNode.insertBefore(div, textarea)
// Upddatera
setInterval('resize()', 200)
}
function resize()
{
text = textarea.value.htmlescape().replace(/\n/g, '<br>')
.replace(/ /g, '&emsp;')
// Bufferthöjd
+ '<br>'.repeat(2) + '&nbsp;'
div.innerHTML = text
textarea.style.height = div.offsetHeight + 'px'
}
// Byter ut speciella HTML-tecken mot deras entiteter
String.prototype.htmlescape = function()
{
return this.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;')
}
// Upprepar en sträng @i@ gånger
String.prototype.repeat = function(i)
{
return new Array(1 + i).join(this)
}
// Source: http://quirksmode.org/
function getStyle(x, styleProp)
{
return x.currentStyle ? x.currentStyle[styleProp]
: document.defaultView
.getComputedStyle(x, null)
.getPropertyValue(styleProp)
}
</script>
</body>
</html>
@inflx
Copy link

inflx commented Feb 22, 2014

You're my hero.

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