If you want to add multiple rectangles, the first step is either using a different id or setting up the newly created div directly:
$('<div>')
.css({
'position': 'absolute',
'width': rectWidth,
'height': rectHeight,
'left': startX,
'top': startY,
'background': '#000000'
})
.appendTo(this);
Step 1.1 involves changing the position to absolute so that the next elements are not positioned relative to the previously added elements.
Step 2 focuses on preventing overlap. By utilizing the selectable feature, you can easily check if any elements are selected (any divs with the .ui-selected
class) and avoid adding a new rectangle if any elements are currently selected within the stop event callback:
if($(".ui-selected", this).length) return;
Here is an example implementation that introduces a Rect object to manage positions and demonstrates the use of the demo class:
$(function() {
var startingPosition;
function getPosition(e){return {X:e.pageX, Y:e.pageY};}
function Rect(start,stop){
this.left = Math.min(start.X,stop.X);
this.top = Math.min(start.Y,stop.Y);
this.width = Math.abs(stop.X - start.X);
this.height = Math.abs(stop.Y - start.Y);
}
$('#target').selectable({
start: function(e) {
startingPosition = getPosition(e);
},
cancel: '.demo',
stop: function(e) {
if($(".ui-selected", this).length) return;
var rectangle = new Rect(startingPosition,getPosition(e));
$('<div>')
.css({
'width': rectangle.width,
'height': rectangle.height,
'left': rectangle.left,
'top': rectangle.top
})
.addClass('demo')
.appendTo(this);
}
});
});
Check out the Demo fiddle here
As an extra tip, you can easily identify intersecting elements by coloring them red during selection:
.ui-selecting{
background: red;
}