Is it possible to add an eventlistener on a DIV?

76,540

Yeah, that's how you do it.

document.getElementById("div").addEventListener("touchstart", touchHandler, false);
document.getElementById("div").addEventListener("touchmove", touchHandler, false);
document.getElementById("div").addEventListener("touchend", touchHandler, false);

function touchHandler(e) {
  if (e.type == "touchstart") {
    alert("You touched the screen!");
  } else if (e.type == "touchmove") {
    alert("You moved your finger!");
  } else if (e.type == "touchend" || e.type == "touchcancel") {
    alert("You removed your finger from the screen!");
  }
}

Or with jQuery

$(function(){
  $("#div").bind("touchstart", function (event) {
    alert(event.touches.length);
  });
});
Share:
76,540
Roskvist
Author by

Roskvist

Updated on September 06, 2020

Comments

  • Roskvist
    Roskvist over 3 years

    I know this function:

    document.addEventListener('touchstart', function(event) {
        alert(event.touches.length);
    }, false);
    

    But is it possible to add this to a div? Example:

    document.getElementById("div").addEventListener('touchstart', function(event) {
            alert(event.touches.length);
        }, false);
    

    I haven't tested it yet, maybe some of you know if it works?

  • schilippe
    schilippe almost 10 years
    JQuery's bind also takes the third Boolean parameter to handle bubbling. The default is the equivalent of false in the javascript code too so for consistency you should have it either in both listings or none.