Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to add an eventlistener on a DIV?

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?

like image 988
Roskvist Avatar asked Nov 12 '10 11:11

Roskvist


People also ask

Can you add an eventListener to a function?

You can add event listeners to any DOM object not only HTML elements. i.e the window object. The addEventListener() method makes it easier to control how the event reacts to bubbling.

How do I add an eventListener to a checkbox?

To add a checkbox check event listener with JavaScript, we can listen for the change event. to add a checkbox. const checkbox = document. querySelector("input[name=checkbox]"); checkbox.

Can you have more than one addEventListener?

We can invoke multiple functions on a single event listener without overwriting each other. To do this we simply call the addEventListener() method more than once with a different function. In the example above, we add another event listener for the same event on the same button.


1 Answers

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);   }); }); 
like image 82
iRyanBell Avatar answered Sep 20 '22 17:09

iRyanBell