JSFiddle - React, Tailwind, and code Playground

by stevea

HTML

<div id='box1' class='drag'></div>
<div id='box2' class='drag'></div>
<div id='box3' class='drag'></div>
<div id='box4' class='drag'></div>
<div id='group'></div>

CSS

.drag {
    position: absolute;
/*    float: left;  */
    width: 100px;
    height: 100px;
    background: gold;
    margin: 5px;
    z-index: 100
}
#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;
}

JavaScript

$('.drag').draggable();

$('.drag').click(function(){
//    debugger;
    var top;
    var left;
    var data = $(this).data('clicked'); // undefined if not clicked. true if clicked
    var group$ = $('#group');        // short hand for ease
    if(data == undefined || data == false){
        $(this).data('clicked', true);        //  wasn't clicked. mark it clicked
        this.style.opacity = '0.3';
        $(this).draggable('disable');        // no longer draggable on its own
        if(group$.children().length <= 0){    // if no children yet, this is the first
            group$.draggable().css({        // make div.group draggable
                top: '0px',                // position at top left
                left: '0px',
                width: $(window).width(),    // make div.group size of entire window (viewport)
                height: $(window).height(),
                'z-index': 1
            });
        }
        top = parseInt(group$.css('top').replace('px','')) +  // group's top +
                    parseInt($(this).css('top').replace('px',''));        // box's top
        left = parseInt(group$.css('left').replace('px','')) +        // group's left +
                    parseInt($(this).css('left').replace('px',''));        // box's left
        
        $(this).css({
            top: top,
            left: left
        })  
        group$.append($(this));  // move box1 inside of div.group 
    }
    else {        // clicking a clicked element. Move back to body from all
        $(this).data('clicked', false);
        this.style.opacity = '1.0';
        $(this).draggable('enable');        // let box be draggable again on its own
        
        top = parseInt(group$.css('top').replace('px','')) +  // group's top +
                    parseInt($(this).css('top').replace('px',''));        // box's top
        left = parseInt(group$.css('left').replace('px','')) +        // group's left +
                   ...