Search code examples
javascripthtmldrag-and-droptrello

How can I easily duplicate the trello style of drag and drop of cards? (Kanban style app)


I'm building a web app that uses a similar drag and drop metaphor that trello has for moving cards around by dragging and dropping cards from one list to another.

How can I do this?


Solution

  • An upgraded version built upon Brad Parks-s answer right on this very page featuring even more indent and an awesome tilt-towards-drag-direction effect as demonstrated on this jsFiddle page.

    Different bits in JavaScript follow the comments:

    $( ".column" ).sortable({
        connectWith: ".column",
        handle: ".portlet-header",
        cancel: ".portlet-toggle",
        start: function (event, ui) {
            ui.item.addClass('tilt');
            // Start monitoring tilt direction
            tilt_direction(ui.item);
        },
        stop: function (event, ui) {
            ui.item.removeClass("tilt");
            // Unbind temporary handlers and excess data
            $("html").unbind('mousemove', ui.item.data("move_handler"));
            ui.item.removeData("move_handler");
        }
    });
    
    // Monitor tilt direction and switch between classes accordingly
    function tilt_direction(item) {
        var left_pos = item.position().left,
            move_handler = function (e) {
                if (e.pageX >= left_pos) {
                    item.addClass("right");
                    item.removeClass("left");
                } else {
                    item.addClass("left");
                    item.removeClass("right");
                }
                left_pos = e.pageX;
            };
        $("html").bind("mousemove", move_handler);
        item.data("move_handler", move_handler);
    }  
    

    CSS modifications for different tilt degrees

    .tilt.right {
        transform: rotate(3deg);
        -moz-transform: rotate(3deg);
        -webkit-transform: rotate(3deg);
    }
    .tilt.left {
        transform: rotate(-3deg);
        -moz-transform: rotate(-3deg);
        -webkit-transform: rotate(-3deg);
    }