Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply jQuery events to all class elements?

I have the following code which will allowed a user running iOS to move a <div> with the class .drag around on the page. This works fine when there is one istance of .drag, but fails to work when there are two instances of it. Is it possible to have the code find all of the <div>'s, then allow them to be draggable?

var drag = $(".drag")[0];
    xPos = drag.offsetWidth / 2;
    yPos = drag.offsetHeight / 2;
    drag.addEventListener("touchmove", function() {
        event.preventDefault();
        $(this).css({
        'left' : event.targetTouches[0].pageX - xPos + 'px', 
        'top' : event.targetTouches[0].pageY - yPos + 'px'
    });
});
like image 264
Charlie Avatar asked Sep 09 '12 01:09

Charlie


1 Answers

When you use $(selector)[0], you get the first DOM element that matches the selector. Use .each() instead to add the event listener to all elements that match the selector:

$(".drag").each(function () {
    var drag = this;
    xPos = drag.offsetWidth / 2;
    yPos = drag.offsetHeight / 2;
    drag.addEventListener("touchmove", function() {
        event.preventDefault();
        $(this).css({
          'left' : event.targetTouches[0].pageX - xPos + 'px', 
          'top' : event.targetTouches[0].pageY - yPos + 'px'
        });
    });
});​
like image 60
João Silva Avatar answered Oct 05 '22 19:10

João Silva