FRONTEND/Javascript

[JS] textarea 높이 자동 조절

숭코기 2023. 4. 18. 15:14
728x90

 

📌 예제코드

See the Pen Textarea Auto Height by Jeong Seung Yeon (@ssyeon612) on CodePen.

 

 

📌 코드

<textarea id="textarea"></textarea>

높이를 조절할 textarea 요소를 준비해줍니다.

 

textarea {
  width: 240px;
  height: 30px;
}

textarea의 기본 Height를 지정해주고, 이 크기는 JavaScript 코드에서도 사용하게 됩니다.

 

const DEFAULT_HEIGHT = 30; // textarea 기본 height

const $textarea = document.querySelector('#textarea');
  • CSS에서 지정한 Height를 'DEFAULT_HEIGHT' 변수에 저장시켜줍니다.
  • document.querySelector() 선택자로 textarea 요소를 가져와줍니다.

 

// Textarea 자동 높이 조절
$textarea.oninput = (event) => {
  const $target = event.target;

  $target.style.height = 0;
  $target.style.height = DEFAULT_HEIGHT + $target.scrollHeight + 'px';
};
  • oninput 이벤트로 입력 되는 시점을 감지해줍니다.
  • 이때, 해당 textarea의 height를 0으로 변경해주고 scrollHeight 속성으로 스크롤을 포함한 요소의 높이를 적용해줍니다.

 

 

 

먼저 height를 초기화 해주지 않으면, scrollHeight 속성이 기존 스타일 높이까지 누적되어 적용되게 됩니다. 

 

 

728x90