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"> <div class="editor">
<form action="" method="POST"> <form action="" method="POST">
<input type=hidden name=revision value="{{revision}}"> <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> <button type=submit>Save</button>
</div>
</form> </form>
</div> </div>
</article> </article>
@ -30,15 +33,26 @@
</footer> </footer>
<script> <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() { function openEditor() {
const rendered = document.querySelector(".rendered"); const rendered = document.querySelector(".rendered");
const editor = document.querySelector(".editor"); 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"; editor.style.display = "block";
const textarea = editor.querySelector("textarea"); autosizeTextarea(textarea, shadow);
textarea.style.height = (textarea.scrollHeight + 60) + "px"; textarea.addEventListener('input', () => autosizeTextarea(textarea, shadow));
window.addEventListener('resize', () => autosizeTextarea(textarea, shadow));
rendered.style.display = "none";
const form = editor.querySelector("form"); const form = editor.querySelector("form");
form.addEventListener("submit", async function (ev) { form.addEventListener("submit", async function (ev) {
@ -53,6 +67,8 @@ function openEditor() {
} }
); );
}); });
textarea.focus();
} }
document document

View file

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