Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect user touch with phonegap using JS

I am using phonegap to build android apps.

I would like to detect the touch event from a user so I can pop-up an alert. However, how do I call the ontouch event from javascript?

Thanks!

like image 274
Dayzza Avatar asked Jan 28 '11 08:01

Dayzza


1 Answers

Below is an example that shows touchstart and touchend. It demonstrates two different ways to attach touch events: element attributes or JavaScript's addEventListener.

Since it is listening for touch events, the events will not fire on a desktop browser (which supports mouse events). To test the page, you can open it a Android or iOS simulator.

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0;" />
    <style type="text/css">
      a {
        color:black;
        display:block;
        margin:10px 0px;
      }
    </style>

    <script type="text/javascript">
      function onload() {
        document.getElementById('touchstart').addEventListener('touchstart', hello, false);
        document.getElementById('touchend').addEventListener('touchend', bye, false);
      }

      function hello() {
        alert('hello');
      }

      function bye() {
        alert('bye');
      }
    </script>

    <title>Touch Example</title>
  </head>
  <body onload="onload();">
    <h1>Touch</h1>
    <a href="#" ontouchstart="hello();return false;">Attribute: ontouchstart</a>
    <a href="#" ontouchend="bye();return false;">Attribute: ontouchend</a>
    <a href="#" id="touchstart">addEventListener: touchstart</a>
    <a href="#" id="touchend">addEventListener: touchend</a>
  </body>
</html>
like image 132
mwbrooks Avatar answered Nov 01 '22 10:11

mwbrooks