user31782
user31782

Reputation: 7589

How to use mobile touch events with pure javascript?

What is the syntax for mobile touch events in javascript? I tried:

window.document.body.ontouchstart = function() { alert(); }

and

window.document.body.touchstart = function() { alert(); }

It doesn't give any error. And nothing happens on touching the webpage. It seems like addEventListener is the way to go. But why doesn't window.document.body.ontouchstart directly work?

Upvotes: 1

Views: 6957

Answers (2)

Tiago Fabre
Tiago Fabre

Reputation: 787

Try this code:

function foo(event) {
  alert();
}

var el = document.getElementsByTagName("canvas")[0];
  el.addEventListener("touchstart", foo(), false);

//or 

window.document.body.addEventListener("touchstart", foo(), false);

Upvotes: 1

Dimppy
Dimppy

Reputation: 83

var theElement = document.getElementById("theElement");

theElement.addEventListener("touchstart", handlerFunction, false);

function handlerFunction(event) {
alert();
}

Upvotes: 3

Related Questions