JSFiddle - React, Tailwind, and code Playground

by stevea

HTML

<div id='box1' class='box'></div>
<div id='box2' class='box'></div>
<div id='box3' class='box'></div>
<div id='box4' class='box'></div>
<div id='group'></div>        <!--  group plane  -->

CSS

.box {
    position: absolute;
    width: 100px;
    height: 100px;
 
    background: black;
    z-index: 100      /* keep boxes above group so we can select them  */
}
#box1 {
    left:10px;
    top: 15px;
}
#box2 {
    left:150px;
    top:25px;
}
#box3 {
    left:300px;
    top:35px;
}
#box4 {
    left:450px;
    top:45px;
}


#group {
    width: 100%;
    height: 100%;
    z-index: -1;
    position: absolute;
    background-color:#CFFBE1; /* so we can see group plane move */
    opacity:0.5;
}

JavaScript

$('.box').draggable();
$('#group').draggable();  // make group plane draggable

$('.box').click(function(){
    var this$=$(this);

    if(!this$.hasClass('clicked')){
        this$.addClass('clicked')      // not clicked yet, mark clicked to join group
             .css('opacity', '0.5')     // dim to show box is now in group
             .draggable('disable');     // disable box's own draggable
        $('#group').append(this$);      // move box onto group plane
    }
})

$('#group').click(function(){
    group$ = $('#group');
    group$.find('.clicked').each(function() {
 //       debugger;
        this$ = $(this);
        this$.removeClass('clicked')
               .css('opacity', '1.0')        // bring back full color
               .draggable('enable');        // let box be draggable again on its own
         /*
           Add group plane offset to box offset
        */
        var gp_top = parseInt(group$.css('top').replace('px',''));
        var box_top = parseInt(this$.css('top').replace('px','')); 
        var top = gp_top + box_top;
        
        var gp_left = parseInt(group$.css('left').replace('px',''));
        var box_left = parseInt(this$.css('left').replace('px',''));  
        var left = gp_left + box_left;
        this$.css({
            top: top,
            left: left
        })
        $('body').append(this$);     // move box off of group plane back to body
    });
    group$.css({top: '0px', left: '0px'  }); // reset group plane to top left   
});