I found the code below but the text area height grows at the bottom.
backspace increases value of scrollheight
How could I grow it from top to up direction?
It is for a chat application I am building, and this would be the typing area.
I spent some time on the net looking for the solution but it apparently is not that easy.
Edit: Looking at how the snipped behaves here in stackoverflow, I am thinking now that it may be related with how the parent wrapper is set on css, but still do not know how to fix it.
document.querySelectorAll('textarea').forEach( element => {
element.style.height = `${element.scrollHeight}px`;
element.addEventListener('input', event => {
event.target.style.height = 'auto';
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>Data Management</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script type="module" src="script.js" defer></script>
</head>
<body>
<header>
<h1>Growing textarea</h1>
</header>
<main>
<p><textarea id="article" ></textarea></p>
</main>
</body>
</html>
CodePudding user response:
For expanding the textarea to the top you can use position:absolute
and bottom: 0
in a container with position:relative
. This way the text-area will always stick to the bottom of the container with 0
margin.
Also, you can set the default rows of the textarea to 1 to look like a text input when the text fits inside one line:
<textarea rows="1"></textarea>
document.querySelectorAll('textarea').forEach( element => {
element.style.height = `${element.scrollHeight}px`;
element.addEventListener('input', event => {
event.target.style.height = 'auto';
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;
position:absolute;
bottom:0
}
main{
position: relative;
}
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>Data Management</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script type="module" src="script.js" defer></script>
</head>
<body>
<header>
<h1>Growing textarea</h1>
</header>
<main>
<textarea rows="1" id="article"></textarea>
</main>
</body>
</html>