Search code examples
javascripttouch

JavaScript onTouch not working


Can anybody tell me why this onTouch handler isn't firing.

var myDiv = document.getElementById('existingContent');
var myButton = '<a href="#" onClick="logOut();" ontouch="logOut()">log out</a>';
myDiv.appendChild(myButton);

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

I am using iPad 1.


Solution

  • My recommendation would be the same as the one proposed here on MDN:

    var el = document.getElementsByTagName("canvas");  
    el.addEventListener("touchstart", handleStart, false); 
    

    My hesitation with the ontouch attribute is cross-device support. For this you might consider feature detection.

    Modernizr is a popular way to determine if touch is enabled at runtime.

    If the events above are enabled, the classes touch or no-touch would be added to the html element and used to determine if the code above should run.

    EDIT:

    In subsequent days I ran across this document describing Touch Events. As with much of technology, there is still more to it...