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!
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!
Share Improve this question edited Mar 4, 2012 at 10:13 Waynn Lue 11.4k8 gold badges52 silver badges77 bronze badges asked Jan 28, 2011 at 8:28 DayzzaDayzza 1,5577 gold badges18 silver badges30 bronze badges1 Answer
Reset to default 16Below 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>