javascript – How to create an object for Multitouch correctly?

Question:

I wrote a function for multitouch, but it's a little crooked. My function is used so that you can move the squares ( div elements) with your fingers in several pieces, depending on the number of touches. But the problem is that the function has to be called for each element separately, which is not very convenient, since the code grows in size, plus, perhaps, there will be more divs themselves.

Here is an example of a function for 2 elements:

var obj = document.getElementById('elem_1');
obj.addEventListener('touchmove', function(event) {
  if (event.targetTouches.length == 1) {
    var touch = event.targetTouches[0];
    obj.style.left = touch.pageX + 'px';
    obj.style.top = touch.pageY + 'px';
  }
}, false);

var obj2 = document.getElementById('elem_2');
obj2.addEventListener('touchmove', function(event) {
  if (event.targetTouches.length == 1) {
    var touch = event.targetTouches[0];
    obj2.style.left = touch.pageX + 'px';
    obj2.style.top = touch.pageY + 'px';
  }
}, false);

How can you adapt a function to any number of elements?

Answer:

Give each square a class (for example .js-multitouch ), and replace the code in js with:

$(document).ready(function() {
  var elements = $('.js-multitouch');
  if (elements.length) {
    elements.each(function(e) {
      var element = $(this)
      element.bind('touchmove', function(event) {
        if (event.targetTouches.length == 1) {
          var touch = event.targetTouches[0];
          element[0].style.left = touch.pageX + 'px';
          element[0].style.top = touch.pageY + 'px';
        }
      });
    });
  }
});

The script uses jQuery. It does not appear in your code, but the question has a jquery label, which means, if I understand correctly, you can use it.

Working example on jsfiddle

Scroll to Top