오늘의 강의에서는 다음과 이전 버튼의 이벤트를 걸어주기로 했다.
슬라이더의 전체적인 스크립트는 ImageSlider.js 파일을 생성한 뒤, class를 작성하기로 했다.
class ImageSlider {
#currentPosition = 0; // 현재 슬라이더의 위치
#slideNumber = 0; // 슬라이드의 개수
#slideWidth = 0; // 슬라이드의 너비
sliderWrapEl;
sliderListEl;
nextBtnEl;
previousBtnEl;
// class에서 인스턴스가 만들어질때 실행되도록 넣어줌
constructor() {}
// element 담아둠
assignElement() {
this.sliderWrapEl = document.getElementById('slider-wrap'); // #slider-wrap
this.sliderListEl = this.sliderWrapEl.querySelector('#slider'); // ul#slider
this.nextBtnEl = this.sliderWrapEl.querySelector('#next'); // button#next
this.previousBtnEl = this.sliderWrapEl.querySelector('#previous'); // button#previous
}
}
필요한 변수들을 선언하고 assignElement 메서드에 필요한 엘리먼트들을 찾아서 담아둔다.
slider-wrap을 제외한 요소들은 document부터 찾는 것이 아니라 slider-wrap에서부터 찾도록 로직을 작성하기로 했다.
지난 프로젝트에서도 그랬듯이 리소스를 낭비하지 않기 위해서이다.
주석에서 참조할수있듯이 현재 슬라이더의 위치, 슬라이더의 개수와 크기도 변수로 선언해준다.
// slideNumber 초기화 메서드
initSliderNumber() {
this.#slideNumber = this.sliderListEl.querySelectorAll('li').length;
// sliderList의 li의 개수가 slideNumber의 값이 된다
}
// slideWidth 초기화 메서드
initSlideWidth() {
this.#slideWidth = this.sliderListEl.clientWidth;
// slide의 크기를 sliderWrap의 크기로 초기화
}
// sliderListWidth 초기화 메서드
initSliderListWidth() {
this.sliderListEl.style.width = `${this.#slideNumber * this.#slideWidth}px`;
// sliderList의 너비를 slide의 개수에 따라 동적으로 변화시킴
// slide 개수 * slide의 너비
}
슬라이더의 개수, 슬라이더의 너비, 슬라이더 리스트의 너비를 초기화 하는 메서드를 작성한다.
sliderNumber는 ul.slider의 li 개수로 초기화시켜준다.
slideWidth는 sliderList의 너비로 초기화한다.
sliderList의 width는 slide의 개수에 따라 동적으로 변할수있도록 코드를 작성한다.
템플릿 리터럴을 사용해 slideNumber * slideWidth를 게산해 초기값을 설정하도록 했다.
// 이벤트 메서드 작성
addEvent() {
this.nextBtnEl.addEventListener('click', this.moveToRight.bind(this));
this.previousBtnEl.addEventListener('click', this.moveToLeft.bind(this));
}
moveToRight() {
this.#currentPosition += 1;
// 범위제한
if (this.#currentPosition === this.#slideNumber) {
this.#currentPosition = 0;
}
this.sliderListEl.style.left = `-${
this.#slideWidth * this.#currentPosition
}px`;
// currentPosition의 값에 -1000씩 곱한 값을 ul.slider에 left 값으로 준다.
// = 왼쪽방향으로 슬라이드 크기만큼 이동시킴
// 0 > 0 / 1 > -1000 / 2 > -2000 ...
}
moveToLeft() {
this.#currentPosition -= 1;
// 범위 제한
if (this.#currentPosition === -1) {
this.#currentPosition = this.#slideNumber - 1;
}
this.sliderListEl.style.left = `-${
this.#slideWidth * this.#currentPosition
}px`;
}
이제 이벤트 메서드를 작성한다.
nextBtn에는 moveToRight 메서드를, previousBtn에는 moveToLeft 메서드를 이벤트 핸들러로 넣어주었다.
moveToRight 메서드가 실행되면, currentPosition이 1씩 증가한다.
그리고 sliderListEl의 left 속성을(현재 0) 변경시켜주도록 작성한다.
sliderList의 left가 변경되면 슬라이드가 오른쪽에서 왼쪽으로 당겨지는 것처럼 동작하게 된다.
따라서 슬라이드의 너비 * 현재 슬라이드의 위치 값을 통해 작성할 수 있다.
또한 currentPosition이 슬라이드 개수보다 작거나 커질경우를 대비해 범위 제한을 작성했다.
currentPosition이 slideNumber와 같아지면(=마지막 슬라이드에서 다음 버튼을 누르게 되면) 맨 처음 슬라이드로 돌아가도록 하고, currentPosition이 -1이 되면(=첫번째 슬라이드에서 prev 버튼을 누르면) 맨 마지막 슬라이드로 이동하게 했다.
moveToLeft도 같은 방식으로 작성했다.
여기까지 작성하게 되면 슬라이드가 이렇게 부드럽게 작동하는 것을 볼 수 있다.
***************************************
#패스트캠퍼스 #패캠챌린지 #수강료0원챌린지 #환급챌린지 #직장인인강 #직장인자기계발
#패캠인강후기 #패스트캠퍼스후기 #오공완 #30개프로젝트로배우는프론트엔드withReact
본 포스팅은 패스트캠퍼스 환급 챌린지 참여를 위해 작성되었습니다.
'study > fastcampus' 카테고리의 다른 글
[React] 이미지 슬라이드 - 4. 인디케이터 (0) | 2023.02.28 |
---|---|
[React] 이미지 슬라이드 - 2. HTML & CSS (0) | 2023.02.26 |
[React] 이미지 슬라이드 - 1. 프로젝트 개요 및 개발환경 설정 (0) | 2023.02.25 |
[React] 가상 키보드 만들기 - 5. 마우스 이벤트 작성 (0) | 2023.02.24 |
[React] 가상 키보드 만들기 - 4. 키보드 이벤트 작성 (0) | 2023.02.23 |