Skip to content

Instantly share code, notes, and snippets.

@nolanlawson
Last active September 14, 2019 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nolanlawson/8388d97091b8a50e218da0e59f7bcc81 to your computer and use it in GitHub Desktop.
Save nolanlawson/8388d97091b8a50e218da0e59f7bcc81 to your computer and use it in GitHub Desktop.
textarea with pre mirror to autosize
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>resize textarea</title>
<style>
textarea.textarea, pre.mirror {
border: 1px solid gray;
margin: 0;
padding: 0;
}
textarea.textarea {
resize: none;
}
.container {
position: relative;
width: 300px;
min-height: 50px;
}
.textarea, .mirror {
left: 0;
right: 0;
top: 0;
width: 100%;
position: absolute;
font-size: 14px;
font-weight: normal;
}
.textarea {
min-height: 50px;
}
.mirror {
pointer-events: none;
white-space: pre-wrap;
word-wrap: break-word;
}
</style>
</head>
<body>
<div class="container">
<pre class="mirror"></pre>
<textarea class="textarea"></textarea>
</div>
<script>
(function () {
'use strict'
var $ = document.querySelector.bind(document)
var $textarea = $('.textarea')
var $mirror = $('.mirror')
var update = function () {
$mirror.innerHTML = $textarea.value + '<br/>'
}
update()
$textarea.addEventListener('input', update)
var height
var observer = new ResizeObserver(function (entries) {
var newHeight = entries[0].contentRect.height
if (newHeight !== height) {
$textarea.style.height = newHeight + 'px'
height = newHeight
}
})
observer.observe($mirror)
})()
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment