더보기 버튼
v.1
const btnMores = document.querySelectorAll('.btn-more'); btnMores.forEach(function (btnMore) { const toggleBox = btnMore.nextElementSibling; // btn-more의 바로 옆에 있는 toggle-wrap btnMore.addEventListener('click', function (event) { event.stopPropagation(); // 다른 활성화된 toggle-wrap 비활성화 document.querySelectorAll('.toggle-wrap.active').forEach(function (box) { if (box !== toggleBox) { box.classList.remove('active'); } }); // 현재 toggle-wrap의 활성화 상태를 토글 toggleBox.classList.toggle('active'); }); });
기존 코드는 화면이 변경되면 동작을 하지 않아서 아래 MutationObserver 적용함
v.2
// btn-more와 toggle-box 처리 함수
function setupToggleButtons() {
document.querySelectorAll('.btn-more').forEach(function (btnMore) {
if (btnMore.dataset.eventAdded) return; // 이미 이벤트가 추가된 요소는 제외
btnMore.dataset.eventAdded = true; // 중복 방지 플래그 설정
const toggleBox = btnMore.nextElementSibling; // btn-more의 바로 옆에 있는 toggle-wrap
btnMore.addEventListener('click', function (event) {
event.stopPropagation();
// 다른 활성화된 toggle-wrap 비활성화
document.querySelectorAll('.toggle-wrap.active').forEach(function (box) {
if (box !== toggleBox) {
box.classList.remove('active');
}
});
// 현재 toggle-wrap의 활성화 상태를 토글
toggleBox.classList.toggle('active');
});
});
}
// 최초 실행
setupToggleButtons();
// MutationObserver를 이용하여 DOM 변경 감지
const observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
if (mutation.type === 'childList') {
setupToggleButtons(); // 새로운 요소가 추가될 때 다시 실행
}
});
});
// body의 변화 감지 (자식 요소 추가/삭제 감지)
observer.observe(document.body, { childList: true, subtree: true });