Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I do a two finger drag with javascript/jquery?

I'm trying to create the ability to drag a div when there are two fingers placed on it.

I've bound the div to the touchstart and touchmove events. I'm just not sure how to write the functions.

Something like if event.originalEvent.targetTouches.length => 2 set starting X and Y.

Do I average the two fingers positions? Then apply css transforms with the data? How do I pull it out of the flow of the DOM, static positioning?

Any examples would be great, thanks!

like image 423
fancy Avatar asked Mar 27 '26 11:03

fancy


1 Answers

In CoffeeScript, I also edited it to use globals for the purpose of generalizing. I'm not using global variables.

    $('#div').bind 'touchstart', touchstart
    $('#div').bind 'touchmove', touchmove

    touchstart: (event) =>
        if event.originalEvent.touches.length >= 2

            x = 0
            y = 0

            for touch in event.originalEvent.touches
                x += touch.screenX
                y += touch.screenY

            window.startx = x/event.originalEvent.touches.length
            window.starty = y/event.originalEvent.touches.length

    touchmove: (event) =>
        if event.originalEvent.touches.length >= 2

            x = 0
            y = 0

            for touch in event.originalEvent.touches
                x += touch.screenX
                y += touch.screenY

            movex = (x/event.originalEvent.touches.length) - @startx
            movey = (y/event.originalEvent.touches.length) - @starty

            newx = $('#div').offset().left + movex
            newy = $('#div').offset().top + movey

            $('#div').offset({top: newy, left: newx})

            window.startx = x/event.originalEvent.touches.length
            window.starty = y/event.originalEvent.touches.length
like image 71
fancy Avatar answered Mar 29 '26 01:03

fancy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!