I'm trying to implement a simple script to manage resizing the textarea to fit the content. It works perfectly when adding content but every time I press the backspace key the scrollheight value increases by 3px!
document.querySelectorAll('textarea').forEach( element => {
element.style.height = `${element.scrollHeight}px`
element.addEventListener('input', event => {
event.target.style.height = `${event.target.scrollHeight}px`
})
})
/* style.css */
main, header {
max-width: 600px;
margin: auto;
}
textarea {
font-family: 'Times New Roman', Times, serif;
font-size: 1em;
border-style: hidden;
outline: none;
padding: 0.1em;
margin: none;
resize: none;
width: 80%;
border-radius: 0.2em;
border: 1px solid #EEE;
}
textarea:focus {
border: 1px solid #DDD;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf8" />
<meta name="viewport" content="width=device-width", initial-scale="1.0" />
<title>Resizing Text Area</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script type="module" src="./script.js" defer></script>
</head>
<body>
<header>
<h1>Resizing Text Area</h1>
</header>
<main>
<p><textarea class="data p" id="article"></textarea></p>
</main>
</body>
</html>
Does anyone know the cause of this annoying behaviour?