I am working on a demo where page have selectable jQuery for creation square block(area).
User can select any area and write some comment with color, entire block will be shown specify position. It working fine.
But my main concern is if someone select same area or selecting area with contain already exists blocks.How i can restrict it.
The first step for adding multiple rectangles, is to either use another id, or setup the created div directly:
$('<div>')
.css({
'position': 'relative',
'width': width,
'height': height,
'left': beginX,
'top': beginY,
'background': '#000000'
})
.appendTo(this);
step 1.1 is to make the position absolute, so the subsequent elements are not positioned relational to the other added elements.
Step 2 is preventing overlap. Since the selectable is used, this can be done quite easily by checking if any elements are selected (any divs with the .ui-selected
element) and don't add the new rectangle in case any are selected inside the stop event callback:
if($(".ui-selected", this).length)return;
An example implementation (took the liberty of introducing a Rect object to contain the positions, but that isn't obligatory. same with the demo class)
$(function() {
var startpos;
function getpos(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);
}
$('#tar').selectable({
start: function(e) {
startpos = getpos(e);
},
cancel: '.demo',
stop: function(e) {
if($(".ui-selected", this).length) return;
var rect = new Rect(startpos,getpos(e));
$('<div>')
.css({
'width': rect.width,
'height': rect.height,
'left': rect.left,
'top': rect.top
})
.addClass('demo')
.appendTo(this);
}
});
});
edit: as an extra, an easy indication can be given of an intersect by colouring every element that would be 'selected red':
.ui-selecting{
background: red;
}