Easy Java Script Drag n Drop Code
By Stephen Bucaro
One of the most interesting features you can use on your webpage is the ability
to drag and drop graphics. Unfortunately the implementation of drag and drop is
not compatible between browsers, not even between different versions of Internet
Explorer. For this reason the only examples you can find are over-complicated
with provisions for browser compatibility.
The ability to drag and drop graphics on a webpage can allow you to create online
training material, games, greeting card makers, and other interesting applications.
In this article, I show you an easy way to implement drag and drop graphics
that works on Internet Explorer.
The first step is to put a tiny bit of style code in the head section of your
webpage, as shown below.
<head>
<style>
.circle
{
position: absolute;
cursor: hand;
}
</style>
<head>
Next put html code for your graphic in the body section of your webpage, as shown below.
<img src="redball.gif" class="circle">
Note how the class attribute of the img tag was set to the name of the style class
that you created above. Next put a tiny bit of JavaScript code in the head section
of your webpage, just below the style code block. The JavaScript code is shown below.
<script language="JavaScript">
var obj;
var dragging = false;
var objx, objy, mx, my;
</script>
This code just declares some variables we will use. "obj" is a variable for saving the
graphic object. "dragging" is a boolean flag that will be set to "true" while dragging,
and "false" when we stop dragging. The other variables are for saving the x and y coordinates
of the graphic and the mouse pointer.
Lets get one more boring thing out of the way before we get into the interesting stuff.
Place the following code in the JavaScript code block, just below the variables.
function cancelEvent()
{
window.event.returnValue = false;
}
This function disables a browser event. The event that we want to disable is Internet
Explorers built-in drag and drop events. Those events are far too complicated to use in
this example, but they interfere with our simple code. To disable the built-in drag and
drop events, call the cancelEvent function from your image tag as shown below.
<img ondragstart="cancelEvent()" src="redball.gif" class="circle">
Now for the interesting part. We are going to add three simple functions to the
JavaScript code block just below the code that we already added. The "pick" function
is called when you pick a graphic to drag. The "drag" function is called by mousemove
events while you are dragging. The "drop" function is called when you drop the graphic.
The code for the pick function is shown below.
function pick()
{
if(event.srcElement.className == "circle")
{
// save loc of image
obj = event.srcElement;
objx = obj.style.pixelLeft;
objy = obj.style.pixelTop;
// save loc of mouse pointer
mx = event.clientX;
my = event.clientY;
dragging = true;
}
}
|