Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select area/rectangle in javascript

I need to select a region in an HTML5 page via the mouse.

I'm then going to interact with the elements within that region.

There MUST be an easy way to do it but I couldn't find anything off the shelf..

The jquery UI selection didn't work unfortunately because it seems to only support one parent element.

Is there anything off the shelf to draw a transparent div over a region with a dashed outline?

Or an easy implementation. I could probably spend a couple of hours and bang something out but I'm surprised there's nothing that allows me to do it in 5 minutes.

like image 535
burtonator Avatar asked Apr 25 '14 04:04

burtonator


2 Answers

Seems simple enough…

Create a div that's initially hidden:

<div id="div" hidden></div>

Style it:

#div {
    border: 1px dotted #000;
    position: absolute;
}

And the JS:

var div = document.getElementById('div'), x1 = 0, y1 = 0, x2 = 0, y2 = 0;
function reCalc() { //This will restyle the div
    var x3 = Math.min(x1,x2); //Smaller X
    var x4 = Math.max(x1,x2); //Larger X
    var y3 = Math.min(y1,y2); //Smaller Y
    var y4 = Math.max(y1,y2); //Larger Y
    div.style.left = x3 + 'px';
    div.style.top = y3 + 'px';
    div.style.width = x4 - x3 + 'px';
    div.style.height = y4 - y3 + 'px';
}
onmousedown = function(e) {
    div.hidden = 0; //Unhide the div
    x1 = e.clientX; //Set the initial X
    y1 = e.clientY; //Set the initial Y
    reCalc();
};
onmousemove = function(e) {
    x2 = e.clientX; //Update the current position X
    y2 = e.clientY; //Update the current position Y
    reCalc();
};
onmouseup = function(e) {
    div.hidden = 1; //Hide the div
};

http://jsfiddle.net/jLqHv/

like image 109
bjb568 Avatar answered Sep 19 '22 20:09

bjb568


I've created a library for exactly this purpose: https://github.com/Simonwep/selection

There's currently full desktop and mobile / touch support as well as auto-scroll functionality as you know from your file explorer :)

like image 29
Simon Avatar answered Sep 18 '22 20:09

Simon