Keep textarea automatically sized to fit its contents

This commit is contained in:
Magnus Hoff 2017-09-04 13:47:12 +02:00
parent 84b97efa9d
commit 0bc4c69579
2 changed files with 45 additions and 8 deletions

View file

@ -9,8 +9,11 @@
<div class="editor">
<form action="" method="POST">
<input type=hidden name=revision value="{{revision}}">
<textarea name=body>{{raw}}</textarea>
<textarea autocomplete=off name=body>{{raw}}</textarea>
<textarea autocomplete=off class="shadow-control"></textarea>
<div class="editor-controls">
<button type=submit>Save</button>
</div>
</form>
</div>
</article>
@ -30,15 +33,26 @@
</footer>
<script>
function autosizeTextarea(textarea, shadow) {
shadow.value = textarea.value;
shadow.style.width = textarea.clientWidth + "px";
shadow.style.height = "auto";
textarea.style.height = shadow.scrollHeight + "px";
}
function openEditor() {
const rendered = document.querySelector(".rendered");
const editor = document.querySelector(".editor");
const textarea = editor.querySelector('textarea[name="body"]');
const shadow = editor.querySelector('textarea.shadow-control');
rendered.style.display = "none";
editor.style.display = "block";
const textarea = editor.querySelector("textarea");
textarea.style.height = (textarea.scrollHeight + 60) + "px";
autosizeTextarea(textarea, shadow);
textarea.addEventListener('input', () => autosizeTextarea(textarea, shadow));
window.addEventListener('resize', () => autosizeTextarea(textarea, shadow));
rendered.style.display = "none";
const form = editor.querySelector("form");
form.addEventListener("submit", async function (ev) {
@ -53,6 +67,8 @@ function openEditor() {
}
);
});
textarea.focus();
}
document

View file

@ -135,17 +135,38 @@ textarea {
monospace;
width: 100%;
height: 1000px;
resize: none;
overflow: hidden;
}
.shadow-control {
visibility: hidden;
position: fixed;
}
.editor {
display: none;
}
button[type="submit"] {
.editor-controls {
position: fixed;
right: 20px;
bottom: 20px;
right: 0;
bottom: 0;
left: 0;
background: #91A238;
padding: 10px 20px;
}
@media (min-width: 600px) {
.editor-controls {
position: fixed;
left: auto;
right: 20px;
bottom: 20px;
box-shadow: 5px 5px 8px rgba(0,0,0, 0.3);
}
}
</style>
</head>