새소식

반응형
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

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.