The ability to drag and drop graphics on 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.
Bucaro TecHelp Maintain Your Computer and Use it More Effectively to Design a Web Site and Make Money on the Web
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.
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
var dragging = false;
var objx, objy, mx, my;
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.
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.
Now for the interesting part. We are going to add three simple functions to the
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.
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;