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.

  • 5
    what you have tried? Post Code – Manwal Apr 25 '14 at 4:52

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
onmousemove = function(e) {
    x2 = e.clientX; //Update the current position X
    y2 = e.clientY; //Update the current position Y
onmouseup = function(e) {
    div.hidden = 1; //Hide the div


  • Is hidden really a boolean attribute on <div>s? – Ry- May 31 '14 at 1:22
  • @false Yup. The fiddle works, doesn't it? – bjb568 May 31 '14 at 1:24
  • I wouldn’t know; jsFiddle hasn’t worked for me for a while. Anyways, cool! hidden seems like a useful addition. – Ry- May 31 '14 at 1:27
  • 3
    @minitech HTML5 defines that attribute: developer.mozilla.org/en-US/docs/Web/HTML/… – John Dvorak Jul 19 '14 at 15:10
  • great that's works fine – kaxi1993 Apr 4 '16 at 5:05

I've created a library for exactly this subject: 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 :)

Your Answer

