2

I have an image and I need to measure how long user touch the image or has mouse pressed on the image. So I use mouse down event to to get the start time and mouse up event to get the finish time. However, when running on android device, the long touch triggers the context menu to pop up, which I don't want. I can hide the context menu by adding function on context menu event and return false from it. The context menu is blocked and not displayed. BUT the mouse up event does not triggered either.

How to block context menu and still have mouse up event?

Jsfiddle [here][1]

  [1]: https://jsfiddle.net/vghk9q53/5/
Mikhail Chibel
  • 1,865
  • 1
  • 22
  • 34

2 Answers2

2

Instead of using mousedown and mouseup you should use touchstart and touchend

Mazz
  • 1,859
  • 26
  • 38
0

Answering my own question. I got confused by my colleague who said that browsers are smart enough to convert touch events into mouse events, which is not true. To solve the problem, I need to additionally listen for touch end event as pointed by @Mazz. JsFiddle for the solution

<body>
  <img id="image" src="https://launchbit.com/carbon-i/6496-ZenHubCarbon.png" alt="" border="0" height="100" width="130" style="max-width: 130px;">
  <textarea id="text" rows="25"></textarea>
  <script>
    function printOutput(txt) {
      console.log(txt);
      document.getElementById("text").value = document.getElementById("text").value + txt + "\n";
    }
    window.addEventListener("load", function(event) {
      document.getElementById("image").oncontextmenu = function() {
        printOutput("context menu");
        return false;
      };
      document.getElementById("image").addEventListener("mousedown", function() {
        printOutput("mouse down");
      });
      document.getElementById("image").addEventListener("mouseup", function() {
        printOutput("mouse up");
      });
      document.getElementById("image").addEventListener("touchstart", function() {
        printOutput("touchstart");
      }, false);
      document.getElementById("image").addEventListener("touchend", function() {
        printOutput("touchend");
      }, false);
      document.getElementById("image").addEventListener("touchcancel", function() {
        printOutput("touchcancel");
      }, false);
      document.getElementById("image").addEventListener("touchmove", function() {
        printOutput("touchmove");
      }, false);
    });
  </script>
</body>
Mikhail Chibel
  • 1,865
  • 1
  • 22
  • 34