jQuery select set and drag

by craic

HTML

<div id="box0" class="box"></div>
<div id="box1" class="box"></div>
<div id="box2" class="box"></div>
<div id="box3" class="box"></div>

<div id="msg0"></div>
<div id="msg1"></div>

CSS

.box {
    width: 50px;
    height: 50px;
    border: 1px solid black;
    position: absolute;
}

#box0 {
    left: 50px;
    top:  100px;
    background-color: #e00; 
}
#box1 {
    left: 150px;
    top:  100px;
    background-color: #ee0; 
}
#box2 {
    left: 250px;
    top:  100px;
    background-color: #e0e; 
}
#box3 {
    left: 350px;
    top:  100px;
    background-color: #0ee; 
}

JavaScript

var box_ids = [ '#box0', '#box1', '#box2', '#box3' ];

var boxes = $(".box").get();

$('#msg0').text(boxes.length + ' boxes');

var selected = [];
var drag = {
    elem: null,
    color: null,
    x: 0,
    y: 0,
    state: false
};
var delta = {
    x: 0,
    y: 0
};

$.each(boxes, function(i, node) {

    $(this).mousedown(function(e) {
        //this.style.backgroundColor = '#f00';
        if(e.shiftKey) {
            // SELECT mode
            if(selected[this.id] != null) {
                // Already selected
//$('#msg0').text(this.id + ' >' + selected[this.id] + '< '+ ' removing');

   // null, undefined or something else?
                
                selected[this.id] = null;
                this.style.border = '1px solid black';

            } else {
                // Not in selection
//$('#msg0').text(this.id + ' >' + selected[this.id] + '< '+ '  adding');

                selected[this.id] = this.id;
                this.style.border = '2px solid black';

            }
        } else {
            // DRAG mode
            // need to distinguish between single and selected array
            if (!drag.state) {
                drag.elem = this;
                drag.color = this.style.backgroundColor;

                this.style.backgroundColor = '#f00';
                drag.x = e.pageX;
                drag.y = e.pageY;
                drag.state = true;
            }
            return false;

        }
        
        var str = '';
        for(var j in selected) {
            if(selected[j] != null) {
                str = str + ' ' + selected[j];
            }
        }
        $('#msg1').text(str);

        return false;
    });

    $(this).mouseup(function(e) {
        //this.style.backgroundColor = '#ff0';
        if(e.shiftKey) {
            // SELECT mode
        } else {
            // DRAG mode
        }
    });
    
});


// mousemove and mouseup are bound to the document

$(document).mousemove(function(e) {
    if (drag.state) {

       ...