Search code examples
javascriptjquerydrag-and-drophtml5-canvasdrag

Drag a profile image inside a div but it does not work in mobile


I have taken a codepen reference https://codepen.io/dsalvagni/pen/BLapab to drag a profile image. But it doesn't work in mobile. Getting this error in mobile "[Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See ". I tried adding third parameter passive:false. But did not work. Can anyone please help me out. Thanks in advance! Adding code snippet below that I tried to change so that it works in mobile.

    $(window).on("mousemove touchmove", function (e) {
    e.preventDefault();
    if ($dragging) {
      var refresh = false;
      clientX = e.clientX;
      clientY = e.clientY;
      if (e.touches) {
        clientX = e.touches[0].clientX;
        clientY = e.touches[0].clientY;
       }

      var dy = clientY - y;
      var dx = clientX - x;
      dx = Math.min(dx, 0);
      dy = Math.min(dy, 0);
      /**
       * Limit the area to drag horizontally
       */
      if (self.model.width + dx >= self.model.cropWidth) {
        self.model.x = dx;
        refresh = true;
      }
      if (self.model.height + dy >= self.model.cropHeight) {
        self.model.y = dy;
        refresh = true;
      }
      if (refresh) {
        render();
      }
    }
  },{ passive: false });

Solution

  • Now I understood your question; to drag profile image. You meant as to pan it around.

    So jQuery can't add support to passive listeners. The work around is to use native addEventListener. To support multiple events, I just add array with event names, then use forEach() to run both events.

    ['mousemove', 'touchmove'].forEach(evt =>
        window.addEventListener(evt, function(e) {}, {
          passive: false
        })
    

    This will remove the error, but then, still one more to change in the code as your reference is in dragStart() function. JQuery modified the original events, and store it in e.originalEvent. if you just use e.touches, there is no such object in e, you have to look inside e.originalEvent

    Here is the full example with amendment to your reference code, because SO can't add more than 3000 characters