Skip to content

Instantly share code, notes, and snippets.

@thekid
Last active June 12, 2023 21:04
Show Gist options
  • Save thekid/cbaf408feea074aaa5092352f7deaeee to your computer and use it in GitHub Desktop.
Save thekid/cbaf408feea074aaa5092352f7deaeee to your computer and use it in GitHub Desktop.
Automatically resizing textarea
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Input</title>
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
<style>
#prompt {
font-family: 'Roboto', sans-serif;
line-height: 1.5;
font-size: 1.15rem;
padding: .25rem;
width: 100%;
min-height: 2rem;
max-height: 10rem;
overflow-y: scroll;
border: .15rem solid slategray;
border-radius: .25rem;
white-space: pre-wrap;
}
</style>
</head>
<body>
<form method="POST">
<input type="hidden" name="prompt">
<div id="prompt" contenteditable="true">{{prompt}}</div>
<input type="submit" value="submit">
</form>
</body>
<script type="module">
const $input = document.getElementById('prompt');
// Copy content to form element
const $hidden = document.querySelector(`form input[name="${$input.id}"]`);
$hidden.form.addEventListener('submit', (e) => {
$hidden.value = $input.innerText;
});
// When using copy&paste, strip all HTML
const plainText = 'text/plain';
$input.addEventListener('paste', (e) => {
e.preventDefault();
const text = e.clipboardData.getData(plainText);
if (text.length > 0) {
document.execCommand('insertText', false, text);
}
});
</script>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Input</title>
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
<style>
textarea {
font-family: 'Roboto', sans-serif;
line-height: 1.5;
font-size: 1.15rem;
padding: .25rem;
width: 100%;
overflow-y: hidden;
}
</style>
</head>
<body>
<textarea title="Input" id="prompt" rows="1" data-max-rows="5"></textarea>
</body>
<script type="module">
const $input = document.getElementById('prompt');
const style = window.getComputedStyle($input);
const padding = parseInt(style.getPropertyValue('padding'), 10) * 2;
const lines = parseInt(style.getPropertyValue('line-height'), 10) * parseInt($input.dataset.maxRows);
$input.addEventListener('input', (e) => {
e.target.style.height = 'auto';
const height = e.target.scrollHeight - padding;
if (height > lines) {
e.target.style.height = lines + 'px';
e.target.style.overflowY = 'scroll';
} else {
e.target.style.height = height + 'px';
e.target.style.overflowY = 'hidden';
}
});
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment