Javascript carousel

jooog·2021년 9월 13일
0

carousel이란?

웹사이트에서 흔하게 확인할 수 있는 carousel을 자바스크립트로 구현하고 싶었다.

그런데 carousel이 정확히 뭘까?

구글링을 해보니 캐러셀은 이미지 로테이터, 슬라이더 등으로 불리며 같은 공간에 하나 이상의 콘텐츠를 보여주는 것을 말한다고 한다

다양한 라이브러리가 많지만 바닐라 자바스크립트로 구현해보자

<div class="description">   
  <p>111 Lorem ipsum dolor sit amet</p>
</div>

<div class="description">   
  <p>111 Lorem ipsum dolor sit amet</p>
</div>

<div class="description">   
  <p>111 Lorem ipsum dolor sit amet</p>
</div>

내 프로젝트에서 사용한 코드를 간단하게 가져왔다

.showing {
    z-index: 30;
    opacity:0.7;
}

showing class를 만들어 놓고 이제 자바스크립트로 carousel을 본격적으로 구현해보자

const SHOWING_CLASS = "showing";
const firstSlide = document.querySelector('.description');


firstSlide.nextElementSibling.classList.add(SHOWING_CLASS);


const slide = () => {
    const currentSlide = document.querySelector(`.${SHOWING_CLASS}`);

    if (currentSlide) {
        currentSlide.classList.remove(SHOWING_CLASS);
        const nextSlide = currentSlide.nextElementSibling;

        if (nextSlide) {
            nextSlide.classList.add(SHOWING_CLASS)
        } else {
            firstSlide.classList.add(SHOWING_CLASS);
        }
    } else {
        firstSlide.classList.add(SHOWING_CLASS);
    }
    
};

slide();
setInterval(slide, 3000);

먼저 firstSlide에 description element를 담아둔다

firstSlide element의 nextElementSibling으로 그 다음 두번째 element를 가져올 수 있다

 if (currentSlide) {
        currentSlide.classList.remove(SHOWING_CLASS);
        const nextSlide = currentSlide.nextElementSibling;

        if (nextSlide) {
            nextSlide.classList.add(SHOWING_CLASS)
        } else {
            firstSlide.classList.add(SHOWING_CLASS);
        }
    } else {
        firstSlide.classList.add(SHOWING_CLASS);
    }
    
};

코드를 자세히 살펴보자

const currentSlide = document.querySelector(`.${SHOWING_CLASS}`);

showing이 붙은 element가 있으면 showing class를 제거하고
그 다음 element를 찾아 showing class를 붙여주는 방식이다

setInterval(slide, 3000);

setInterval로 slide 함수를 일정 간격으로 호출한다

이렇게 자바스크립트를 사용하여 간단하게 carousel 효과를 구현했다

0개의 댓글