HTML and CSS Reference
In-Depth Information
See Also
The beginner's guide provides an introduction to applicationCache functionality at
http://www.html5rocks.com/en/tutorials/appcache/beginner/ . For more in-depth infor-
mation on the applicationCache API, see this MDC entry: https://developer.mozilla.org/
en/offline_resources_in_firefox . In addition, http://appcachefacts.info has a great dis-
cussion of important nuances of appcache behavior.
10.3 Drag and Drop
Problem
You want to implement native drag-and-drop functionality without managing mouse
events manually or using a complex library.
Solution
Recognizing how common drag-and-drop interaction is in today's complex web ap-
plications, HTML5 now defines a direct API for handling drag and drop (“D&D”).
To test if the browser supports native D&D functionality, use the following feature-
detect:
var dnd_support = 'draggable' in document.createElement('span');
Now, let's build a simple D&D demo. We'll begin by setting up some visual styles for
our D&D elements:
<style>
#foobar { background-color:yellow; width:100px; height:100px; cursor:move; }
#catcher { background-color:blue; width:150px; height:150px; padding:5px;
margin-bottom:5px; }
</style>
The first step in enabling native D&D is to put the draggable attribute on the element
you want to be drag-enabled:
<div id="catcher">...</div>
<div id="foobar" draggable="true" >...</div>
Next, we need to use the JavaScript API and D&D events to tell the browser where the
element can be dragged to and what to do once it's dropped there.
For example, we can listen for the dragstart event, and style the element differently
when it's being dragged (e.g., putting a border around it or making it partially
transparent):
var foobar = document.getElementById("foobar");
foobar.addEventListener( "dragstart" , function(evt) {
this.style.border = "3px dotted #000"; // black dotted-line border
}, false);
 
Search WWH ::




Custom Search