...

View Full Version : Mouse drag selection box



spiriad
06-23-2009, 05:13 PM
Hello there,

What I want to know is how can I make a drag selection box using JavaScript. What I mean, is when you click the left mouse button and drag, a "wire" (I don't know the term for it) should appear , like on your desktop. I'm sure this is possible, but I didn't find any example.So , can you help me ?

Yours,
Adi

itsallkizza
06-23-2009, 05:58 PM
Here I got you started:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Test</title>
<style type="text/css">
#sel_box
{
display: none;
position: absolute;
border: 1px solid #000000;
background: transparent;
width: 0;
height: 0;
}
</style>
<script type="text/javascript">
// <![CDATA[

function getCursorPosition(e)
{
e = e || window.event;
if (e)
{
if (e.pageX || e.pageX == 0) return [e.pageX,e.pageY];
var dE = document.documentElement || {};
var dB = document.body || {};
if ((e.clientX || e.clientX == 0) && ((dB.scrollLeft || dB.scrollLeft == 0) || (dE.clientLeft || dE.clientLeft == 0))) return [e.clientX + (dE.scrollLeft || dB.scrollLeft || 0) - (dE.clientLeft || 0),e.clientY + (dE.scrollTop || dB.scrollTop || 0) - (dE.clientTop || 0)];
}
return null;
}

function mousedown(e)
{
var mxy = getCursorPosition(e);
var box = document.getElementById("sel_box");
box.orig_x = mxy[0];
box.orig_y = mxy[1];
box.style.left = mxy[0]+"px";
box.style.top = mxy[1]+"px";
box.style.display = "block";
document.onmousemove = mousemove;
document.onmouseup = mouseup;
}

function mousemove(e)
{
var mxy = getCursorPosition(e);
var box = document.getElementById("sel_box");
box.style.width = (mxy[0]-box.orig_x)+"px";
box.style.height = (mxy[1]-box.orig_y)+"px";
}

function mouseup(e)
{
var box = document.getElementById("sel_box");
box.style.display = "none";
box.style.width = "0";
box.style.height = "0";
document.onmousemove = function(){};
document.onmouseup = function(){};
}

document.onmousedown = mousedown;

// ]]>
</script>
</head>
<body>

<div id="sel_box"></div>

</body>
</html>


I left a little work for you to do though. The above code will only work for left to right/top to bottom click+drags, you'll need to do some simple math to make it work universally. You'll also want to put your selection's action code inside the mouseup function.

spiriad
06-23-2009, 06:11 PM
Thanks a lot ! This is what I was looking for !



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum