HTML and CSS Reference
In-Depth Information
When something is dropped on the drop element, it triggers
the drop event and you're able to read the event.dataTransfer
object. The default data type is Text , so you can use the getData
method and ask for the Text data type. In the case of an image,
the text will be the source of the image (typically IE gives us
null for the Text data type, but you'll fix that later). For links, the
href is the set data and for plain text that's been selected and
dragged, the text itself is the set data.
Here's where it starts to get a little strange. To tell the browser
that the drop element can accept items being dropped on it,
you need to cancel the dragover event. Since I'm using an
inline event handler (namely ondragover ) I can return false .
This prevents the default browser action. What is the default
action? It's unclear from the spec, but it would be fair to say the
default action would be to leave the object in the control of the
browser. If I were using addEventListener , I would have to use
event.preventDefault() .
So that you're completely clear—because, frankly, it's not terribly
obvious—here's a quote from the spec:
“If the drop is to be accepted, then this event (dragover) has to
be canceled.”
So now that you've got your first drag and drop working, what
about those tweaks I mentioned? Let's fix Firefox first; this is
easy. When you drop the image on the drop zone in Firefox, it
actually redirects the browser of to the value of getData('Text')
for you if it looks like a link—that is, image sources and link
href s. So that's easy: In the drop event, you prevent the brows-
er's default action. If you're using inline handlers, you'll return
false, or event.preventDefault() , so our drop handler now
looks like this:
drop.ondrop = function (event) {
this.innerHTML += '<p>' + event.dataTransfer.getData
¬ ('Text') + '</p>';
return false;
};
Now, IE. Getting it working in IE isn't actually as painful as it
could be. This is most likely because they came up with the
API in the first place. IE doesn't listen to the dropover event, it
listens for the dropenter event—and it's this event you need to
cancel for IE to play ball. So let's add another event handler and
 
Search WWH ::




Custom Search