스와이퍼 사용법 - (1) Observer로 클래스에 따른 제어 하기

Dustin Jung·2025년 3월 7일

웹퍼블리싱 공부

목록 보기
3/20

<script>

function initSwiper() {
  var swiper = new Swiper(".skill-swiper", {
      slidesPerView: 3.5,
      spaceBetween: 30,
      centeredSlides: true,
      observer: true,  // Swiper가 DOM 변경을 감지할 수 있도록 설정
      observeParents: true, // Swiper의 부모 요소 변경도 감지
      allowTouchMove: true, // 기본적으로 터치 가능
      on: {
        init: () => {
          var swiper_wrapper = document.querySelector('.skill-swiper-wrapper');

          // MutationObserver로 "active" 클래스 추가 감지
          // MutationObserver는 DOM 요소의 변경을 감지하는 API
          // 이걸 사용하면 HTML 요소의 속성(class, style 등)이나 자식 요소가 변경될 때 자동으로 특정 함수를 실행 가능 .
        
          const observer = new MutationObserver(() => { // 콜백 함수 안에서 .skill-swiper-wrapper 요소에 "active" 클래스가 있는지 확인.
              if (swiper_wrapper.classList.contains('active')) {
                  swiper.allowTouchMove = false; // 터치 이동 비활성화
              } else {
                  swiper.allowTouchMove = true; // 터치 이동 활성화
              }
              // "active" 클래스가 추가되면 allowTouchMove = false;,
              // "active" 클래스가 없어지면 allowTouchMove = true;
              swiper.update(); // Swiper에게 변경 사항을 반영하도록 업데이트 실행
          });

          // observer 실행 (class 속성 감시)
          observer.observe(swiper_wrapper, { attributes: true, attributeFilter: ['class'] }); // observe(타겟, 옵션)을 사용해서 swiper_wrapper의 변경을 감시 시작
          // attributes: true → class, style 같은 속성이 변경될 때 감지
          // attributeFilter: ['class'] → "class" 속성만 감지하도록 설정 (불필요한 감지 방지)

        }
      }
  });
}

</script>

가정 => 다른 요소에서 스와이퍼에 active 클래스가 주어졌을 때만 스와이프 기능을 막고 싶다면,

클래스를 감지하는 observer와 allowTouchMove: true / false로 관리하면 된다.

여기서 swiper 자체의 observer: true와 observeParents: true는 DOM요소의 변화를 감지하는 기능이다.

즉, 동적으로 새로운 slide가 추가된다면, 이를 감지해 자동 새로고침을 하는 기능.

그러나 지금 쓴 예제같은 경우처럼 단순 클래스 추가는 감지해주지 않는다.

그래서 init 으로 함수를 열고 observer기능을 켜야 한다!

이 경우, swiper는 자동 업데이트가 되지 않기 때문에 update는 필수다.

profile
더스틴 정입니다

0개의 댓글