I am trying to make a drag & drop events (to move text) in my webpage. It is working fine in the big screens, but when I try it on small screens (less than 480) the event fires, but the text either disappears or the touch grabs the screen behind the div (the body of the page itself)
JS
let x = 0;
let y = 0;
const ele = document.getElementById("textOverImage");
if (innerWidth <= 480) {
ele.addEventListener('touchstart', handleStart, false);
ele.addEventListener('touchend', handleEnd, false);
ele.addEventListener('touchmove', handleMove, false);
function handleStart(s) {
console.log('touch started');
x = s.clientX;
y = s.clientY;
document.querySelector("#lock_image").addEventListener('touchmove', handleMove);
document.querySelector("#lock_image").addEventListener('touchend', handleEnd);
};
function handleMove(s) {
console.log('touch moved');
const dx = s.clientX - x;
const dy = s.clientY - y;
ele.style.top = `${ele.offsetTop + dy}px`;
ele.style.left = `${ele.offsetLeft + dx}px`;
ele.classList.remove('centered');
ele.classList.remove('customClass');
ele.classList.add('customMovement');
x = s.clientX;
y = s.clientY;
};
function handleEnd() {
console.log('touch ended');
document.querySelector("#lock_image").removeEventListener('touchmove', handleMove);
document.querySelector("#lock_image").removeEventListener('touchend', handleEnd);
};
}
if (window.innerWidth <= 480){
ele.addEventListener('touchstart', handleStart, false);
ele.addEventListener('touchend', handleEnd, false);
ele.addEventListener('touchmove', handleMove, false);
function handleStart(s){
s.preventDefault();
x = s.touches[0].clientX;
y = s.touches[0].clientY;
console.table(x, y);
document.querySelector("#lock_image").addEventListener('touchmove', handleMove);
document.querySelector("#lock_image").addEventListener('touchend', handleEnd);
};
function handleMove(s){
s.preventDefault();
const dx = s.touches[0].clientX - x;
const dy = s.touches[0].clientY - y;
ele.style.top = `${ele.offsetTop + dy}px`;
ele.style.left = `${ele.offsetLeft + dx}px`;
ele.classList.remove('centered');
ele.classList.remove('customClass');
ele.classList.add('customMovement');
x = s.touches[0].clientX;
y = s.touches[0].clientY;
};
function handleEnd(s){
s.preventDefault();
document.querySelector("#lock_image").removeEventListener('touchmove', handleMove);
document.querySelector("#lock_image").removeEventListener('touchend', handleEnd);
};
}