I'm trying to move an element on the page using the pageX
value of a touch event. I put two console.log
statements in the code below to track the pageX
value - the first outputs the pageX
value in the touchstart
function, and the second continuously tracks the pageX
value within the touchmove
function as my finger is moved across the screen.
I'm expecting the pageX
value from the touchmove
function to change continuously as I'm moving my finger, but it's just continuously outputting the same thing that the touchstart
function output. For instance, if the output of the touchstart
console.log
is 256.55
for the pageX
value, then the touchmove
console.log
will just continuously output a stream of the value 256.55
, which is where I would expect this value to change.
I've tried removing the event.preventDefault();
statement, which is just sort of a guess as to something that would prevent pageX
from updating? But that didn't change anything.
Is the pageX
value even the right value to track for continuous x position?
// event listener on an image that gets touched
lightboxImages[i].addEventListener('touchstart', touchMove);
function touchMove(event) {
console.log(touch.pageX);
event.preventDefault();
var touchedImage = event.target;
var touch = event.touches[0];
var moveOffsetX = touchedImage.offsetLeft - touch.pageX;
touchedImage.addEventListener('touchmove', function() {
console.log(touch.pageX);
var positionX = touch.pageX + moveOffsetX;
touchedImage.style.left = positionX + 'px';
}, false);
}
Most of this code taken from: https://www.youtube.com/watch?v=_3b1rvuFCJY
EDIT: I've refactored the code into two separate functions, like this:
// event listeners on an image that gets touched
lightboxImages[i].addEventListener('touchstart', touchStart);
lightboxImages[i].addEventListener('touchmove', touchMove);
function touchStart(event) {
event.preventDefault();
touchedImage = event.target;
touch = event.touches[0];
moveOffsetX = touchedImage.offsetLeft - touch.pageX;
console.log(touch.pageX);
}
function touchMove(event) {
console.log(touch.pageX);
var positionX = touch.pageX + moveOffsetX;
//touchedImage.style.left = positionX + 'px';
touchedImage.style.left = touch.pageX + 'px';
}
..but still experiencing the same problem.
I figured out that assigning touchstart
's pageX
value to a variable does not get changed within touchmove
, so I had to just assign touchmove
's event.touches[0]
to its own variable, like so:
function touchStart(event) {
event.preventDefault();
touchedImage = event.target;
touch = event.touches[0];
moveOffsetX = touchedImage.offsetLeft - touch.pageX;
}
function touchMove(event) {
// rather than trying to access variable touch from the touchstart function, I had to get event.touches[0] from touchmove's event
var movedTouch = event.touches[0];
var positionX = movedTouch.pageX + moveOffsetX;
touchedImage.style.left = positionX + 'px';
}