Search code examples
javascriptjquerytwitter-bootstraptwitter-bootstrap-3touch

How to make buttons recognize "Drag" as "Click"


I'm trying to make buttons with Bootstrap 3 for touch UI. My product is for people who are not familiar with touch devices, so users tend to press buttons "deeply". When buttons are pressed deeply, a finger "position" on screen is slipped and browsers (like chrome) recognize buttons dragged. When buttons start to be pressed, buttons are activated, but when slipped, buttons are deactivated and click is canceled.

What I want to do is making buttons that perform as clicked even if users press buttons with slip.

How can I do this?

Here is my sample code. Please look it on a touch device or a touch simulator on browser.


Solution

  • Thank you for your helpful comments. Finally I found the answer:

    const $touchButton = $(".touch-button");
    
    $touchButton.on("mousedown touchstart", e => {
      const $button = $(e.currentTarget);
      $button.addClass("active");
    });
    
    $touchButton.on("touchmove", e => {
      const $button = $(e.currentTarget);
      $button.addClass("touch-button--touchmoving");
    });
    
    $touchButton.on("touchend", e => {
      const $button = $(e.currentTarget);
      $button.removeClass("active");
      if($button.hasClass("touch-button--touchmoving")) {
        $button.click();
        $button.removeClass("touch-button--touchmoving");
      }
    });
    
    $touchButton.on("mouseup", e => {
      const $button = $(e.currentTarget);
      $button.removeClass("active");
    });
    
    $touchButton.on("mouseleave", e => {
      const $button = $(e.currentTarget);
      $button.removeClass("active");
    });
    
    $touchButton.on("contextmenu", e => {
      return false;
    });
    
    $touchButton.on("click", e => {
      alert("世界一!");
    });
    .touch-button {
      background-color: #169632;
      box-shadow: 0px 8px 0px 0px rgba(13,87,30,1);
      border: none;
      outline: none;
    }
    
    .touch-button.active {
      margin-top: 8px;
      box-shadow: none;
    }
    
    .container {
      margin: 10px;
    }
    
    #my-button {
      border-radius: 8px;
      padding: 16px;
      color: white;
      font-size: 20px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="container">
      <button id="my-button" class="touch-button">日本の米は</button>
    </div>