command 및 commandfor
위 글을 읽었는데, 좋은 기능인거 같아 나중에 사용하기위해서 정리하는 글을 작성합니다.
📌 command
와 commandfor
가 왜 나왔을까?
기존에는 버튼이 다른 요소를 제어할 때, 항상 JavaScript로 이벤트를 직접 처리해야 했습니다. 이 방식은 매번 비슷한 코드를 반복하게 만들어서 불편했고, 접근성(Accessibility)을 유지하기 위해 수동으로 여러가지 속성들을 설정해야 했습니다.
예를 들어:
<!-- 예전 방식 (불편한 방식!) -->
<button id="openBtn" aria-expanded="false">팝업 열기</button>
<div id="popup" style="display:none;">
팝업 내용
</div>
<script>
const btn = document.getElementById("openBtn");
const popup = document.getElementById("popup");
btn.addEventListener("click", () => {
const isOpen = btn.getAttribute("aria-expanded") === "true";
popup.style.display = isOpen ? "none" : "block";
btn.setAttribute("aria-expanded", String(!isOpen));
});
</script>
위와 같이 매번 JavaScript로 상태를 관리해야 했던 복잡한 상황이 있었습니다.
✅ 이제 command
와 commandfor
를 쓰면 어떻게 될까?
위의 예시를 간단하게 바꿀 수 있습니다.
브라우저가 JavaScript 코드 없이 자동으로 상태관리를 해줍니다.
▶️ 예시 1: show-popover
로 팝오버 표시하기
<button commandfor="myPopover" command="show-popover">
메뉴 보기
</button>
<div popover id="myPopover">
여기 메뉴가 나타나요!
</div>
- •
버튼을 클릭하면 브라우저가 자동으로
myPopover
라는 요소에showPopover()
메서드를 호출해줍니다.
- •
추가 JavaScript 코드가 필요 없습니다.
- •
접근성 속성(
aria-expanded
)도 자동으로 처리됩니다.
▶️ 예시 2: show-modal
로 모달 창 띄우기
<button commandfor="myDialog" command="show-modal">
로그인 창 열기
</button>
<dialog id="myDialog">
<h2>로그인하세요!</h2>
<button commandfor="myDialog" command="close">닫기</button>
</dialog>
- •
버튼을 클릭하면 모달 창이 열립니다(
dialog.showModal()
자동 호출).
- •
모달 내의 닫기 버튼은 모달을 닫아줍니다(
dialog.close()
자동 호출).
- •
추가 코드 없이 간단히 모달 동작을 구현합니다.
▶️ 예시 3: 팝오버를 열고 닫는 토글(toggle) 버튼 만들기
<button commandfor="profileMenu" command="toggle-popover">
프로필 메뉴
</button>
<div popover id="profileMenu">
<p>내 정보</p>
<p>설정</p>
<p>로그아웃</p>
</div>
- •
클릭할 때마다 메뉴가 열렸다 닫혔다 합니다.
- •
팝오버 상태관리(
aria-expanded
)는 브라우저가 처리합니다.
▶️ 예시 4: 맞춤(custom) 명령어 사용하기
내장된 명령어가 아닌 사용자가 정의한 명령어를 사용할 수도 있습니다.
사용자 정의 명령어는 반드시 --
로 시작합니다.
<button commandfor="image" command="--zoom-in">
확대하기
</button>
<button commandfor="image" command="--zoom-out">
축소하기
</button>
<img src="image.png" id="image" style="transform: scale(1);" />
<script>
const img = document.getElementById("image");
let scale = 1;
img.addEventListener("command", (event) => {
if (event.command === "--zoom-in") {
scale += 0.1;
} else if (event.command === "--zoom-out") {
scale -= 0.1;
}
img.style.transform = `scale(${scale})`;
});
</script>
- •
버튼을 누르면
image
라는 요소에command
이벤트가 전달됩니다.
- •
사용자가 만든 커스텀 로직을 이벤트 리스너에서 처리합니다.
🎯 command
와 commandfor
언제 쓰면 좋을까?
- •
모달, 팝오버 등 UI 컴포넌트의 상태관리와 접근성 관리를 자동화하고 싶을 때
- •
복잡한 JavaScript 코드 없이 선언적(Declarative)으로 UI를 구현할 때
- •
접근성(
aria-expanded
)을 자동으로 관리하고 싶을 때
- •
자주 반복되는 버튼과 컨트롤 요소 사이의 간단한 상호작용을 처리할 때
이러한 새로운 속성을 사용하면 기존보다 훨씬 깔끔하고 간편하게 UI 요소들을 관리할 수 있습니다!