How to Create a Basic JavaScript Drag and Drop Functionality
|
 |
Visited: 3330 |
|
|
| 2.8/5.0 (36 votes total) |
|
|
|
|
by Neville Bonavia May 16, 2006
|
Web sites such as Google Home Page
implement a cool feature which allows the users to drag and drop
portions of the page from one area onto another. This article’s
objective is to explain how this is implemented.
This article describes a practical example that can be accessed by clicking here
(you can use the code by viewing the source and extract the code). The
example illustrates two HTML tables encapsulated into DIV elements,
which is the container element used to move the object on the screen.
The DIV element that will be moved must have its style sheet position
set to ‘absolute’, and then the x and y position can be set up by
setting up the left and top style respectively.
A global variable will hold the reference of the element that is
registered to be moved around the screen and the motion object
registration is triggered by calling function startmove() as soon as the mouse button is pressed over the element. The method accepts two parameters. The first one is the event and the second is the element itself. Method determineMousePosition
determines the mouse cursor’s position from an event object while
taking into consideration whether the Browser is an Internet Explorer
or not.
The clicking position offset is stored in _offsetX and _offsetY
element properties that are dynamically attached to the object upon
registration. The zIndex style is also stored in an
object’s property, because as soon as the object is registered for
motion, it is set to 1000, which moves the object to the front of other
objects.
Moving the object is handled by the body’s event onmousemove so that if the mouse motion can be detected within the entire document structure. If the movingobject variable is not null, then it means that the referenced element must be moved. This is achieved by setting the object’s top and left styles respectively.
In order to avoid the elements to be highlighted, the body’s onselect and onselectstart are set to return false; so that the document will not be selectable.
Note that this is the simplest type of drag and drop implementation,
and has been tested on Internet Explorer, Opera and Firefox Mozilla. |