Reputation: 9830
I'm trying to add a mouse and touch down
and move
event. In the events function, I want to get the clientX
amount. I did the following to get it:
console.log(e.touches[0].clientX || e.clientX);
But I get the following error:
Uncaught TypeError: Cannot read property '0' of undefined
When:
window
.window
. (I also get the correct output though. So it seems like it's the function fires twice.)How can I add a touch and mouse down
and move
event, then get clientX
? I have to add both touch and move event, because on a touchscreen laptop, there's both capability's. (I'm using Chrome.)
var myDiv = document.getElementById('myDiv');
window.addEventListener('mousedown', mouseDownFunction);
window.addEventListener('touchstart', mouseDownFunction);
myDiv.addEventListener('mousemove', mouseMoveFunction);
myDiv.addEventListener('touchmove', mouseMoveFunction);
function mouseDownFunction(e) {
console.log(e.touches[0].clientX || e.clientX);
}
function mouseMoveFunction(e) {
myDiv.innerHTML = e.touches[0].clientX || e.clientX;
}
#myDiv {
width: 100px;
height: 100px;
background-color: orange;
}
<div id="myDiv"></div>
Upvotes: 0
Views: 1475
Reputation: 5466
Here you go :
Make expression as (e.touches && e.touches[0].clientX) || e.clientX
e.touches is undefined therefore you got the error.
var myDiv = document.getElementById('myDiv');
window.addEventListener('mousedown', mouseDownFunction);
window.addEventListener('touchstart', mouseDownFunction);
myDiv.addEventListener('mousemove', mouseMoveFunction);
myDiv.addEventListener('touchmove', mouseMoveFunction);
function mouseDownFunction(e) {
console.log((e.touches && e.touches[0].clientX) || e.clientX);
}
function mouseMoveFunction(e) {
myDiv.innerHTML = (e.touches && e.touches[0].clientX) || e.clientX;
}
#myDiv {
width: 100px;
height: 100px;
background-color: orange;
}
<div id="myDiv"></div>
Upvotes: 2