Search code examples
javascriptandroidcsstouch-event

Moving an image when the user moves the finger over document


I want to move an image in mobile devices on touch, like when ever user moves the finger over page, image keep moving and always stay at the user finger position, something like web cursor, i am using this code:

 document.addEventListener('touchmove', this.onMouseMove);
 document.addEventListener('touchStart', this.onMouseMove);
 document.addEventListener('touchEnd', this.onMouseMove);

and

onMouseMove = (e) => {
   const img = document.getElementById('drawing-mouse-pointer');
   img.style.left = `${e.touches[0].clientX}px`;
   img.style.top = `${e.touches[0].clientY }px`;
   console.log(e.touches[0] && e.touches[0].clientY);
}

but the image only move once when user click and then stops. how can i keep moving the image with touch.


Solution

  • Generally I would recommend using a library for this like Interact.js, so instead of what you did, you could do the following:

    interact('.draggable')
      .draggable({
      // enable inertial throwing
      inertia: true,
      // keep the element within the area of it's parent
      restrict: {
        restriction: "parent",
        endOnly: true,
        elementRect: { top: 0, left: 0, bottom: 1, right: 1 }
      },
      // enable autoScroll
      autoScroll: true
    });
    

    Where draggable is the classname of the object you want to move. Also, I want to note that in your code, you were attaching event listeners to the document like so document.addEventListener('touchmove', this.onMouseMove); This adds the event listener to the document, not any particular object, so it wouldn't really help you move individual elements. If you want to attach an event to a specific element, you need to reference that element like so:

    let el = document.getElementById('my-el');
    el.addEventListener('touchmove', onMouseMove);