CATEGORY

카테고리 (576)
AI (2)
Language (251)
WEB (143)
App (45)
Git (6)
AWS (15)
DataBase (44)
OS (33)
Tool (15)
IT (17)
CodePen (2)
SEEMINGLY ONLINE

Seemingly
Online

이모저모 방방곡곡 두루두루 개발지식 저장소

RECENT POSTS

WEB/JavaScript

[JavaScript] textArea 자동 크기 조절 방법 (resize)

2023-09-22


사진: Unsplash 의 Mo


1. 방법

 

숨겨진 textarea의 auto 설정으로 새롭게 입력받은 input 값에 따라 높이를 계산하고 이후 실제 textare에 적용한다. 실제 textarea에 바로 적용하지 않는 이유는 바로적용 시 auto 속성 값으로 인해 웹창에 스크롤도 같이 이동하기 때문이다.

 

<textarea cols="120" id="test"  oninput="autoResize(this, 'test_hidden')"></textarea>
<textarea cols="120" id=test_hidden" style="position: absolute; top: -9999px; left: -9999px; visibility: hidden;"></textarea>

아래 triggerInputEvent는 만약에 페이지 최초 진입시에도 해당 textarea 창을 조절해야 하는 경우 onload와 같은 함수로 해당 트리거를 호출하면 textarea가 자동으로 조절된다.

 

    
    function autoResize(textareaRef, hiddenTextareaId) {
		const hiddenTextarea = document.getElementById(hiddenTextareaId);

		hiddenTextarea.value = textareaRef.value;
		hiddenTextarea.style.height = 'auto';

		textareaRef.style.height = `${hiddenTextarea.scrollHeight}px`;
	}

	function triggerInputEvent(ele, id) {
		let testTextarea = document.getElementById(id);
		if (testTextarea) {
			let currentHeight = parseInt(getComputedStyle(testTextarea).height);
			if (currentHeight > 35) { //자신의 textarea 폰트 사이즈에 맞게
				testTextarea.style.height = '35px' 
			}else{
				testTextarea.dispatchEvent(new Event("input"));
			}
		}
	}

메인 이미지 출처 : 사진: UnsplashMo

COMMENTS