Jump to content

drag function problem


cleary1981

Recommended Posts

Hi all,

 

I am using the drag function below which is from http://dunnbypaul.net/js_mouse/

 

I don't quite understand the code but was wondering if anyone knows how you would alter this code to so that objects being moved move a specified amount of pixels each time. Really the same functionality as snap in the scriptalicious drag drop function.

 

heres the drag function snippet.

function drag(e) // parameter passing is important for NS family 
{
  if (dragobj)
  {
    elex = orix + (mousex-grabx);
    eley = oriy + (mousey-graby);
    dragobj.style.position = "absolute";
    dragobj.style.left = (elex).toString(10) + 'px';
    dragobj.style.top  = (eley).toString(10) + 'px';
  }
  update(e);
  return false; // in IE this prevents cascading of events, thus text selection is disabled
}

Link to comment
https://forums.phpfreaks.com/topic/116198-drag-function-problem/
Share on other sites

Do you mean so that it would move only in squares like a checkers board? Something like this?

<html>
<head>
<script language="JScript">
function dragIt(e)
{
w = parseInt(e.style.width);
h = parseInt(e.style.height);
spotX = parseInt(e.style.left);
spotY = parseInt(e.style.top);
self.document.onmousemove=function()
{
	if ((event.clientX) > spotX+w)
	{
		e.style.left = spotX + w;
		spotX = spotX + w;
	}
	else if ((event.clientX) < spotX)
	{
		e.style.left = spotX - w;
		spotX = spotX - w;
	}
	if ((event.clientY) > spotY+h)
	{
		e.style.top = spotY + h;
		spotY = spotY + h;
	}
	else if ((event.clientY) < spotY)
	{
		e.style.top = spotY - w;
		spotY = spotY - w;
	}
	return false;
}
self.document.onmouseup=function()
{
	self.document.onmousemove=null;
}
}
</script>
</head>
<bodY>
<div id="divTest" STYLE="width:50px;height:50px;background-color:red;display:inline;position:absolute;left:0;top:0" onmousedown="dragIt(this)"></div>
</body>
</html>

Nice one lemmin, that can be reduced greatly by using some math

 

function dragIt(e)
{
w = parseInt(e.style.width);
h = parseInt(e.style.height);

self.document.onmousemove=function()
{
	e.style.left = Math.floor((event.clientX)/w)*w;
	e.style.top = Math.floor((event.clientY)/h)*h;
	return false;
}
self.document.onmouseup=function()
{
	self.document.onmousemove=null;
}
}

You don't. You posted a function and in return you were provided a new function. So, you don't implement this code into that one, you replace that code with this code.

 

Replace the drag() funtion with the dragIt() function. Change the name to 'drag' if you want.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.