O'Reilly logo

JavaScript® 24-Hour Trainer by Jeremy McPeak

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required