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!
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With