jquery에서 touch event 사용하는 방법

jQuery Mobile은 사용하지 않기로 했다.



jquery에서는 mouse 이벤트와 touch 이벤트를 섞어놓았기 때문에, 상황에 따라서는 원하지 않는 결과가 발생하기도 한다 [A].

아래의 예제는 세 개의 영역에 터치 조작을 하도록 구성했는데, 터치 조작이 하나의 영역에서만 일어나고 다른 영역에는 일어나지 않도록 구성하는 것이 쉽지 않았다.



1. 터치하려는 객체를 둔다.

  <body>
    <div class="터치_가능한_객체"> 터치 가능한 객체 1 </div>
    <div class="터치_가능한_객체"> 터치 가능한 객체 2 </div>
    <div class="터치_가능한_객체"> 터치 가능한 객체 3 </div>
  </body>







2. 터치가능한 객체는 굵은 테두리와 넓은 면적을 준다. 터치되면 빨갛게 표시한다.

  <style>
    .터치_가능한_객체 {
      border: 5px solid red;
      min-height:100px;
      margin:30px;
    }
    .터치됨 {
      background-color:red;
    }
  </style>






3. 터치 이벤트를 편리하게 제공받으려면 jquery와 jquerymobile이 필요하다.

  <script
    src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.js">
  </script>
  <script
    src="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.3/jquery.mobile.js">
  </script>








4. jquerymobile을 위한 스크립트는 ready 이벤트에 등록하지 않고 pageinit 이벤트에 등록한다.

  <script>
    $(document).on("pageinit",function(event){
      ...
    });
  </script>






5. 터치 가능한 어떤 하나라도 터치되었음을 표시할 전역 flag를 둔다.

  var 터치됨 = false;






6. 터치 이벤트를 요령껏 관리한다.

한꺼번에 여러군데를 터치했다가 손가락을 떼면 여러개의 touchend 이벤트가 발생한다. 이 중에 하나만이 의미있는 touchend이고 나머지들은 잡음성 이벤트들이다. 이것을 구분해내기위해서 각 터치_가능한_객체에도 "터치됨"이라는 flag를 둔다.

  $(".터치_가능한_객체").on("touchstart", function( event ){
    if( !터치됨 ) {
      터치됨 = this.터치됨 = true;
      $(this).addClass("터치됨");
      event.preventDefault(); /* [A]를 회피하려면 이것이 필요하다 */
      $(this).text('touchstart');
    }
  }); 

  $(".터치_가능한_객체").on("touchend", function( event ){

    if( this.터치됨 ) {
      터치됨 = this.터치됨 = false;
      $(this).removeClass("터치됨");
      $(this).text('touchend');
    }
  }); 



tap, swipeleft, swiperight 이벤트들은 터치가 끝나지 않은 상황에서도 올라온다. 터치된 객체에서 올라오는 이벤트만 의미있는 이벤트이다.

  $(".터치_가능한_객체").on("tap",function(event){
    if( this.터치됨 ) {
      $(this).text("tap");
    }
  });

  $(".터치_가능한_객체").on("swipeleft",function(event){

    if( this.터치됨 ) {
      $(this).text("swipeleft");
    }
  });  

  $(".터치_가능한_객체").on("swiperight",function(event){

    if( this.터치됨 ) {
      $(this).text("swiperight");
    }
  });