Chapter 24. Dragging and Dropping
JavaScript can add rich interactivity to any web page, interactivity that once was available only with conventional applications. For example, take a look at your computer's desktop. Chances are you have one icon that you can click and drag to anywhere you want. That's a level of interactivity that users want, and it would be impossible to supply that interactivity on a web page without JavaScript or plugins like Flash, Silverlight, and so on.
In this lesson, you learn how to:
Get the mouse pointer's location.
Move an element on the page.
Use events to facilitate drag-and-drop.
You then apply this information by writing a drag-and-drop script.
GETTING THE MOUSE POINTER'S LOCATION
For drag-and-drop, the most important piece of information you need is the mouse pointer's coordinates. But you actually need this information represented in two different ways. First you need to know the mouse pointer's coordinates in relation to the page; without them you don't know where to drag the item to.
You also need to know the mouse pointer's position in relation to the HTML element you want to drag. This is important because you want to maintain the mouse pointer's position on the element while you drag it to a new location. Without this information, clicking and dragging an element would result in the element's top left corner snapping to the mouse pointer, as shown in Figure 24-1.
Figure 24.1. Figure 24-1
Let's start by getting the mouse pointer's location in relation ...
Get JavaScript® 24-Hour Trainer now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.