[JavaScript] 터치 슬라이더 구현하기 (touch event)

 

touch event를 사용해 모바일 터치 슬라이더를 구현해본다.

 

HTML

slide-contents 를 감싸는 slide-box가 있고 전체 영역인 slide-wrap으로 구조를 짜놨다.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Welcome</title>
  <link href="css/startPage.css" rel="stylesheet">
</head>
<body>

  <div class="container">
    <div class="slide-wrap">
      <div class="slide-box">
        <section class="slide-contents">
          <h1>오늘의 감정을<br>
              기록할 준비가<br>
              됐나요? 1<br></h1>

          <span>Emoary로 당신의 하루를 기록 해보세요.<br>
                오늘의 감정을 모아 월별로 확인할 수 있어요.</span>
        </section>

        <section class="slide-contents">
          <h1>오늘의 감정을<br>
              기록할 준비가<br>
              됐나요? 2<br></h1>

          <span>Emoary로 당신의 하루를 기록 해보세요.<br>
                오늘의 감정을 모아 월별로 확인할 수 있어요.</span>
        </section>

        <section class="slide-contents">
          <h1>오늘의 감정을<br>
              기록할 준비가<br>
              됐나요? 3<br></h1>

          <span>Emoary로 당신의 하루를 기록 해보세요.<br>
                오늘의 감정을 모아 월별로 확인할 수 있어요.</span>
        </section>
      </div>
    </div>
  </div>

    <article class="button-wrap" onclick="startBtn()">
      <input type="button" value="START" id="start-btn">
    </article>
  </div>

  <script src="script/startPage.js"></script>
</body>
</html>

 

 

CSS

contents의 width값은 300px으로 맞춰주고 box는 position을 relative로 지정해줬다. translateX를 사용하기 위해서이다.

.slide-wrap {
  width: 300px;
  height: 400px;
  margin: 0 auto;
  overflow: hidden;
}

.slide-box {
  display: flex;
  flex-flow: row wrap;
  position: relative;
  margin-top: 150px;
  transform: all 0.5s;
}

.slide-contents {
  width: 300px;
  text-align: left;
  margin: 0 auto;
}

 

 

script

prev, next함수는 각각 뒤로가기, 앞으로가기를 수행하는 함수이다. 사용자가 터치 이벤트를 발생시키면 호출 되도록 한다.

터치 이벤트를 감지하기 위해, addEventListner를 사용한다. touchstart, touchend 이벤트에 대한 이벤트 리스너를 등록해주었는데 이때 이벤트 객체는 터치가 이루어진 지점의 위치를 속성으로 가진다. 이를 통해 스와이프 되었는지 확인할 수 있다. 

let curPos = 0;
let postion = 0;
let start_x, end_x;
const contentsWidth = 300;
const contents = document.querySelector(".slide-contents");

contents.addEventListener('touchstart', touchStart);
contents.addEventListener('touchend', touchEnd);

// 뒤로가기, 앞으로 가기 함수 : 터치 이벤트가 발생(touchEnd())하면 호출 됨
function prev() {
  if (curPos > 0) {
    postion += contentsWidth;
    contents.style.transform = 'translateX(${postion}px)';
    curPos = curPos - 1;
  }
}

function next() {
  if (curPos < 2) {
    position += contentsWidth;
    contents.style.transform = 'translateX(${postion}px)';
    curPos = curPos + 1;
  }
}

function touchStart(e) {
  start_x = e.touchs[0].pageX
}

function touchEnd(e) {
  end_x = e.changedTouches[0].pageX;
  if (start_x > end_x) {
    next();
  } else {
    prev();
  }
}

 

 

 

참고 : https://penguingoon.tistory.com/257