O'Reilly logo

JavaScript & DHTML Cookbook by Danny Goodman

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

Creating a Draggable Element

NN 4, IE 4

Problem

You want a user to be able to click on and drag an element from one location on the page to another.

Solution

Use both the DHTML API from Recipe 13.3 and the dragImg.js library (Example 13-4 in the Discussion) to set up images to drag around the page. The dragImg.js library is wired to expect an img element surrounded by a div element whose class attribute is set to draggable. Moreover, the IDs of related img and div elements must be defined such that the identifier for the div element is the same as the identifier of the img element plus the letters Wrap (the div elements act as wrappers for their img elements). For example, here is the HTML for a pair of images that are set to be draggable:

<div id="imgAWrap" class="draggable"><img id="imgA" name="imgA" src="widget1.jpg" 
width="120" height="90" border="0" alt="Primary draggable widget"></div>
<div id="imgBWrap" class="draggable"><img id="imgB" name="imgB" src="widget2.jpg" 
width="120" height="90" border="0" alt="Secondary draggable widget"></div>

The library actually repositions the div elements, but the mouse events that initiate and control dragging go to the img elements inside the div elements.

Set up the div images to be positioned elements by way of style sheet definitions. For example, the style sheets for the two div elements shown here are as follows:

<style type="text/css"> #imgAWrap {position:absolute; left:50px; top:100px; width:120px; height:90px; border:solid black 1px; ...

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