Kira Kira - 3 months ago 25
Javascript Question

event.target not changed during touchmove in chrome

I have a div with child elements. In touch move, I need the target element. But target element remains same in chrome

Fiddle link:

https://jsfiddle.net/660rdys9/1/




var parent = document.getElementById("parent");
var textbox = document.getElementById("textbox");
parent.ontouchmove = function(e){
textbox.value = e.target.id;
}

div > div{
border:2px solid;
}

<div id="parent" style="width:500px;height:300px;">
<div style="width:500px;height:200px;" id="first">First Span</div>
<div style="width:500px;height:200px;" id="second">Second Span</div>
</div>
<input type="text" id="textbox"/>





Replication Procedure:

1) Goto fiddle in above link using chrome

2) Touch any one of the black rectangle(first div) and move finger to another rectangle(second child div)

3) You can see the id displayed in text box remains same

Is this the behavior of touch move event? is it not possible to get the correct target element during touch move?

Note: event.target is correct during mouse move

Answer

As per the answer in SO question How to find out the actual event.target of touchmove javascript event?, we can use document.elementFromPoint method as workaround

Example code:

var parent = document.getElementById("parent");
var textbox = document.getElementById("textbox");
parent.ontouchmove = function(e){
    var target = document.elementFromPoint(e.originalEvent.changedTouches[0].clientX, e.originalEvent.changedTouches[0].clientY);
	textbox.value = target.id;
}
div > div{
  border:2px solid;
}
<div id="parent" style="width:500px;height:300px;">
<div style="width:500px;height:200px;" id="first">First Span</div>
<div style="width:500px;height:200px;" id="second">Second Span</div>
</div>
<input type="text" id="textbox"/>

Comments