티스토리 뷰

반응형

textarea 자동 높이 조절하는 간단한 방법

웹사이트를 개발하다 보면 종종 textarea의 높이를 자동으로 조절하고 싶을 때가 있습니다. 기본적으로 textarea는 한 줄 또는 몇 줄까지만 표시되고, 내용이 많아지면 스크롤이 생기죠. 하지만 사용자 경험(UX)을 고려한다면, 내용이 많아질 때 자동으로 높이가 조절되는 것이 훨씬 자연스럽습니다.

 

 

오늘은 자바스크립트를 이용해 textarea의 높이를 자동으로 조절하는 방법을 소개하겠습니다. 간단한 코드 몇 줄만으로 깔끔한 UX를 구현할 수 있습니다.

textarea 높이 자동 조절하는 코드

먼저, 아래의 코드를 HTML 파일에 추가해 보겠습니다.

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Textarea 자동 높이 조절</title>
    <style>
        textarea {
            width: 100%;
            min-height: 50px;
            padding: 10px;
            font-size: 16px;
            border: 1px solid #ccc;
            border-radius: 5px;
            resize: none; /* 크기 조절 비활성화 */
            overflow: hidden; /* 불필요한 스크롤바 제거 */
        }
    </style>
</head>
<body>
    <h2>Textarea 자동 높이 조절</h2>
    <textarea id="note" placeholder="내용을 입력하세요..."></textarea>
    <textarea id="aslist" placeholder="추가 메모를 입력하세요..."></textarea>

    <script>
        document.addEventListener("DOMContentLoaded", function() {
            const textarea = document.getElementById("note");
            const textarea_aslist = document.getElementById("aslist");

            function adjustHeight(el) {
                el.style.height = "auto";  // 초기화하여 높이 재계산
                el.style.height = el.scrollHeight + "px"; // 내용에 맞춰 높이 조절
            }

            textarea.addEventListener("input", function() {
                adjustHeight(this);
            });
            adjustHeight(textarea); // 페이지 로드시 높이 조절

            textarea_aslist.addEventListener("input", function() {
                adjustHeight(this);
            });
            adjustHeight(textarea_aslist);
        });
    </script>
</body>
</html>

코드 설명

1. textarea 스타일 설정

  • resize: none; → 사용자가 직접 크기를 조절하지 못하도록 설정합니다.
  • overflow: hidden; → 불필요한 스크롤바가 생기지 않도록 설정합니다.
  • min-height: 50px; → 최소 높이를 설정하여 너무 작아지지 않도록 합니다.

2. 높이 자동 조절하는 JavaScript

function adjustHeight(el) {
    el.style.height = "auto"; // 높이 초기화
    el.style.height = el.scrollHeight + "px"; // 스크롤 높이에 맞춰 조절
}

이 함수는 textarea의 높이를 scrollHeight 값에 맞게 조절합니다. scrollHeight는 요소의 실제 내용 높이를 의미하므로, 자동으로 늘어나거나 줄어들도록 설정할 수 있습니다.

3. 이벤트 리스너 추가

textarea.addEventListener("input", function() {
    adjustHeight(this);
});
adjustHeight(textarea);
  • input 이벤트가 발생할 때마다 adjustHeight 함수를 호출해 높이를 조절합니다.
  • 페이지가 로드될 때 기존 내용이 있다면 높이를 바로 조절합니다.

적용 예시

이제 위 코드를 사용하면 textarea에 글을 입력할 때마다 높이가 자동으로 조절됩니다. 사용자가 편리하게 긴 내용을 입력할 수 있으며, 불필요한 스크롤이 제거되어 깔끔한 디자인을 유지할 수 있습니다.

간단한 몇 줄의 코드만 추가해도 UX가 훨씬 향상되니, textarea를 사용할 때 이 방법을 적극적으로 활용해 보세요!

반응형
댓글