I want the orange rectangle to be draggable using mouse or touch. The function for the mouse is working for me, so I tried copying it and replacing mousedown with ontouchstart, mousemove with ontouchmove and mouseup with ontouchend but it doesn't seem to move. Any suggestions? Thanks!
var move = document.querySelector('.move');
move.addEventListener('mousedown', mousedown);
move.addEventListener('ontouchstart', ontouchstart);
function mousedown() {
move.addEventListener('mousemove', mousemove);
move.addEventListener('mouseup', mouseup);
function mousemove(e){
var x = e.clientX - 100 + 'px';
var y = e.clientY - 100 + 'px';
this.style.left = x;
this.style.top = y;
}
function mouseup() {
move.removeEventListener('mousemove', mousemove)
}
}
function ontouchstart() {
move.addEventListener('ontouchmove', ontouchmove);
move.addEventListener('ontouchend', ontouchend);
function ontouchmove(e){
var x = e.clientX - 100 + 'px';
var y = e.clientY - 100 + 'px';
this.style.left = x;
this.style.top = y;
}
function ontouchend() {
move.removeEventListener('ontouchmove', ontouchmove)
}
}
.move {
height: 200px;
width: 200px;
background: orange;
position: fixed;
}
<body>
<div class="move"></div>
<script src="script.js"></script>
</body>
For one, the names of your events are incorrect. Omit the on
prefix.
Second, touchmove
works a little different from mousemove
. The event parameter that gets passed to touchmove
does not have a clientX
or clientY
property. Instead it contains a TouchList
that needs to be iterated. See below:
var move = document.querySelector('.move');
move.addEventListener('mousedown', mousedown);
move.addEventListener('touchstart', ontouchstart);
function mousedown() {
move.addEventListener('mousemove', mousemove);
move.addEventListener('mouseup', mouseup);
function mousemove(e) {
var x = e.clientX - 100 + 'px';
var y = e.clientY - 100 + 'px';
this.style.left = x;
this.style.top = y;
}
function mouseup() {
move.removeEventListener('mousemove', mousemove)
}
}
function ontouchstart() {
move.addEventListener('touchmove', ontouchmove);
move.addEventListener('touchend', ontouchend);
function ontouchmove(e) {
e.preventDefault();
for (target of e.targetTouches) {
var x = target.clientX - 100 + "px";
var y = target.clientY - 100 + "px";
this.style.left = x;
this.style.top = y;
}
}
function ontouchend() {
move.removeEventListener('touchmove', ontouchmove)
}
}
.move {
height: 200px;
width: 200px;
background: orange;
position: fixed;
}
<body>
<div class="move"></div>
<script src="script.js"></script>
</body>
For more information see Touch Events and Using Touch Events.