Search code examples
javascriptgestures

Tinder style drag gesture and drop with Javascript?


I'm trying to figure out what libraries I can use for a Tinder-style drag and drop gesture that only uses Javascript.

  1. Needs to create an HTML element that responds to a drag gesture..
  2. When touched and held, allows the element to follow the user's finger around.
  3. When the user removes his finger, the element either:

    animates back to its original position

    if the element is over a specified drop zone when it is released, the element will animate and disappear and there needs to be some kind of event that triggers that contains which element was dropped and which drop zone it was dropped into

I've looked into HammerJS but it doesn't seem like there is support for drop zones.

jQuery's Hover event doesn't seem to work for fingers.


Solution

  • My solution for this when I needed to support both desktop and mobile dragging event was to use touch-punch and Jquery-UI.

    It maps the touch events (start/move/end) to the mouse events and for the basic jquery ui draggable features has worked really well. No extra code and i could use draggable and droppable as needed to do the drop, over and out functions.

    For some examples of the drag and drop in jquery UI have a look at http://jqueryui.com/droppable/#revert http://jqueryui.com/draggable/

    these will both work with touch events when including touch-punch on your page along with jquery-ui

    combine with fast-click to remove the 300ms delay in touch events and the lag of dragging can be greatly improved here is an example (example is from jquery-ui just added touch punch and fast click) http://codepen.io/leighquince/pen/ztpCL

    //normal setup from jquery ui
    $(function() {
        $( "#draggable" ).draggable({ revert: "valid" });
        $( "#draggable2" ).draggable({ revert: "invalid" });
    
        $( "#droppable" ).droppable({
          activeClass: "ui-state-default",
          hoverClass: "ui-state-hover",
          drop: function( event, ui ) {
            $( this )
              .addClass( "ui-state-highlight" )
              .find( "p" )
                .html( "Dropped!" );
          }
        });
      });