Udostępnij za pośrednictwem


HTML5 Drag and Drop in IE10 PPB2

Drag and drop is a user interaction model that we all use on a day to day basis,
probably without giving it much thought. We drag files from one folder to another,
text from one area of a document to another, and PowerPoint slides from one place
in the presentation to another.
HTML5 Drag and Drop, available in IE10 Platform Preview 2, brings this natural,
familiar behavior to the Web.
Magnetic Poetry on the IE Test Drive
site is example of a site that uses HTML5 Drag and Drop to create an experience
that previously would have needed a plug-in or JavaScript library.

Screen shot of the "Magnetic Poetry" Test Drive demo.

For an in-depth look at how this demo works,
check out this video.

Before HTML5, drag and drop behavior on the Web only partially worked without JavaScript
frameworks. Now making your site work well with drag and drop is simple.


Making an element draggable

While certain elements can be dragged by default (images, links and selected text),
HTML5 lets you make any element draggable by setting its draggable attribute
to “true.” For example, if you want to make a div draggable you would set its draggable
attribute to “true”; then you can drag that div just like an image. Each magnet
in the Magnetic Poetry demo is a span element with its draggable attribute set to
true.

<span draggable="true"
class="wordMagnet">HTML5</span>

Keep in mind that making an element draggable prevents the user from being able
to select text within that element since any clicks begin a drag.

While you can set the value of the draggable attribute in markup or in script, elements
also have a default draggable state. Images and links default to draggable=true
while all other elements default to draggable=false.


Making an element a drop target

Just like certain elements are draggable by default, certain elements are drop targets
by default. These include text input boxes and contenteditable elements. However,
any element can become a drop target by properly handling the drag events.


Drag Events

When performing a drag operation, you need to consider the element you are dragging
and the element you’re dragging over. Drag events fire on both these elements.

The element being dragged will receive the events:

  • dragstart – the user starts the drag
  • drag – the user is moving the element
  • dragend – the user ends the drag

The element being dragged over will receive the events:

  • dragenter –a drag enters the element’s area
  • dragleave – a drag leaves the element’s area
  • dragover – a drag is moving around the element’s area

The final event – the drop event - fires when the user drops the content. Only input
elements and contenteditable elements receive this event by default. To make other
elements a drop target and receive the drop event, you must call preventDefault()
on the dragenter and dragover events. Here’s an example of making a div a drop target:

<div id="dropTarget">Drop
Here</div>

<script>

function init() {

var dropTarget = document.getElementById("dropTarget");

dropTarget.addEventListener("dragenter",
makeDrop, false);

dropTarget.addEventListener("dragover",
makeDrop, false);

dropTarget.addEventListener("drop",
doSomething, false);

}

 

function makeDrop(e) {

e.preventDefault();

}

</script>

In the Magnetic Poetry demo, when you pick up a magnet (dragstart) the script does
some initial calculations of where within the element the mouse clicked. When you
drop the magnet (dragend) the script calculates a new location for the magnet and
moves it to where you dropped it.

You may also notice that when you drop a magnet, it rotates. The amount of rotation
is based on how close to the middle you grab the magnet. If you grab close to the
middle it will drop fairly flat but if you grab on the edges it will rotate more.
This creates a more natural look.


Accessing Drag Data

When moving the magnets around the fridge, only the magnet, the element being moved,
needed to perform any action so there was no need to exchange data between the element
being dragged and the element being dragged over. Many other drag/drop scenarios,
however, require data exchange between the drag content and the drop target. Consider
a basic kids game where the goal is to drag blocks to the proper holes. When the
hole receives a drop event, it needs to know what was dropped onto it in order to
check if it was the proper shape.

To facilitate exchanging data between the element being dragged and the element
being dropped on, drag events contain a dataTransfer object. Data may be written
to the dataTransfer object only during the dragstart event and it may be read only
during the drop event.

The code for the basic kids block game might look like this:

<div id="circle"
draggable="true"></div>

<div id="triangle"
draggable="true"></div>

<div id="circleHole"></div>

<div id="triangleHole"></div>

 

<script>

function init() {

// register the circle and triangle elements to call
setShape on dragstart

// register circleHole and triangleHole to cancel
the dragenter and dragover events and call checkShape on drop

}

 

function setShape(e) {

e.dataTransfer.setData("text", this.id);

}

 

function checkShape(e) {

var dropped = e.dataTransfer.getData("text");

// check for proper shape...

}

</script>


Drag and drop with files

One last new and really neat part of HTML5 drag and drop is the ability to drag
a file from the desktop to a Web site. When you drop a file on a Web site, it can
read the file contents and use the file within the site. The Magnetic Poetry demo
uses this feature to create small image previews on the refrigerator. Drag an image
file onto the refrigerator and you will get the preview.

Screen shot of the demo showing previews of drag-and-dropped images.

In order to accept file drops, the body of the page has registered for drop events.
When it receives a drop event, it looks at the dataTransfer object to see if there
is content in the files attribute (event.dataTransfer.files). If the drop contained
a file (or multiple files), then the files attribute will contain a
FileList. Each File
in the array can be read through the
FileReader interface. The Magnetic Poetry demo reads the file as a dataURL
and then uses that as the src attribute for a new image that it creates. That way
it can display the image that the user dropped in without ever uploading the file.
Here’s a snippet of the code that gets and reads the file:

function dropHandler(event) {

var filelist = event.dataTransfer.files;

if (!filelist) return;

if (filelist.length > 0) {

var file = filelist[0];

var image = document.createElement('img');

image.src = "";

var filereader = new
FileReader();

filereader.imageElt = image;

filereader.onloadend = handleReaderOnLoadEnd;

filereader.readAsDataURL(file);

}

}

 

function handleReaderOnLoadEnd(event) {

var image = this.imageElt;

image.src = this.result;

document.body.appendChild(image);

}


Accessibility considerations with drag and drop

Drag and drop can be a great interaction mode, however, there are users who can
only use the keyboard and can’t perform a mouse drag and drop operation. If you
create drag and drop experiences, you should always consider how a keyboard user
would be able to complete that task.

The dropzone
attribute
was also added to the HTML5 spec recently in order to identify
areas of the document where items can be dropped. In IE, adding the dropzone attribute
does not automatically make an element a drop target; you still need to handle the
drag events properly as described above. However, using it in your site signals
the drop targets to any accessibility tool that chooses to use it to create more
accessible drag and drop experiences.


Try it out

HTML5 drag and drop is available today in IE10 Platform Preview 2. Try it out for
yourself; you can even share your poem with your friends.

—Sharon Newman, Program Manager, Internet Explorer

Comments

  • Anonymous
    July 27, 2011
    I'm almost sure that drag-and-drop model was supported somehow since IE5. Could you please describe what are the differences between previous and current implementation?

  • Anonymous
    July 27, 2011
    This demo also works in Chrome 12, but not Firefox 5. I'm starting to think the "10 years until you can use HTML5" isn't going to be long enough. :(

  • Anonymous
    July 27, 2011
    JM - you are correct DnD events have been in IE for a while.  New to IE10 is the draggable attribute which enables you to make any element draggable and also the ability to drop files into the browser.  

  • Anonymous
    July 27, 2011
    Thank you for catching up with Chrome and Firefox.

  • Anonymous
    July 27, 2011
    Wonderful! Now, where is history.state? replaceState? and pushState? There is not even a mention of this in the whole blog!!

  • Anonymous
    July 27, 2011
    The comment has been removed

  • Anonymous
    July 29, 2011
    Why do you ignore your users? How many times must we request the option of a separate search bar other than the "onebox" currently being forced on us. Firefox gives us the option to choose. You used to give us flexibility and options. What changed?

  • Anonymous
    July 29, 2011
    CNN Just confirmed it! Internet Explorer users are dumb! www.cnn.com/.../index.html We've all known it all along but no one in major media has ever stated it - until now.  Well done CNN!

  • Anonymous
    July 29, 2011
    @Harry Richter - Microsoft typically writes code to perform in a non-standard way such that it only works in IE but not a modern browser.

  • Anonymous
    July 30, 2011
    @Rob: Can you give us a verifiable example from this blog-article? In what way does the non-standard mark-up succeed in IE10, but fails in FF?

  • Anonymous
    July 30, 2011
    A change more user will notify is that when you drag an image, you'll see a translucent copy of it following your mouse, which is a nice effect some browser had for a while. I give that a +1.

  • Anonymous
    July 30, 2011
    Internet Explorer Team!!!!   News Websites are saying are your users are dumb. :'( I'm a IE user   and I'm Not DUMB! PCMag: www.pcmag.com/.../0,2817,2389463,00.asp Cnn: edition.cnn.com/.../index.html

  • Anonymous
    July 30, 2011
    Another vote for history.pushState (et al).  Implementing what all the other browsers already support seems like it should be a higher priority.

  • Anonymous
    July 30, 2011
    @Mario: Actually, the CNN article indirectly implies that Internet Explorer is the best browser. Why? Because -- as every programmer knows -- it takes far more skill to design a browser for dumb users than smart ones. =P

  • Anonymous
    July 30, 2011
    @FremyCompany, when you post your ticket on connect, can you click on "I can too" link (next to where its written => User(s) can reproduce this bug)? +1 for history.pushState (et al). @shawn, can you manage to open the ticket at connect(connect.microsoft.com/.../feedback) and let me know the number (so I can vote up there)? -1 for the bashers!

  • Anonymous
    July 30, 2011
    The comment has been removed

  • Anonymous
    July 31, 2011
    The comment has been removed

  • Anonymous
    July 31, 2011
    At the flip of the coin, IE is neatly complying with the existing and emerging standards of OPEN WEB much faster than any of yours Goofy Ape browsers. Try using IE9, IE10 ... BTW, for how long you bashers would bash IE for having its 6th version! 1997 is gone.. come on you just hate IE. you are so bile .. as well as jealous.. and You failed! BTW why the heck Chrome auto-updates itself without user intervention in first place (while IE and FF always ask user permission to download the newer verion)! Because its Google and it has all rights to mess with your stuff?? Sloganizing "open-web" doesn’t imply that they are not gonna sell you out someday.. you dump people you will never understand!

  • Anonymous
    August 01, 2011
    @"@Pete&quot;: it seems you are an MS Fanboy (and there's nothing wrong with that) but you are apparently blind to reality so lets talk about some facts shall we? 1.) Chrome auto-updates that is correct (and disclosed when installing it).  You can love or hate it but like all things there are pros and cons to every option.  If Google decided to not auto-update, there would be many who still run old versions of the browser - over time this hurts Chrome as developers still have to support old versions when they shouldn't have to.  The flip side is the IE model where the lack of auto-updates means that there are still millions of people still STUCK on IE6! a browser that was long in the tooth 9 years ago! 2.) IE9 is much better than IE8,7, &6 but it is still a far cry from a standards based browser.  It is only in IE10 (currently in Alpha) that Microsoft has finally fixed things like innerHTML.  This is a bug that's been in IE since BEFORE IE6! (read that once again.. the PRODUCTION version of IE STILL doesn't have proper innerHTML support!).  Due to Microsoft's lack of an auto-update feature web and application developers will have to suffer with this buggy API (and all the other ones) in IE for another decade! 3.) Are we jealous of IE? (yes and no) Yes we are jealous of IE's market share - if only Chrome or Firefox had IE's market share the Web would be miles ahead as developers would be able to legitimately dump support for IE (unfortunately at the moment that's not an option).  However on the flip side it's amazing that other browsers have taken so much market from IE when users have to go out of their way to install Firefox, Chrome, etc. (on windows) to get a better browsing experience. 4.) Do we hate IE? No.  We hate that IE has held back the web for so long.  We hate that we still have to support versions of IE below IE9.  We hate that Microsoft's stance on Video/Audio has ruined the ability for HTML5 Video and Audio to have become a massive success.  We do however get one silver lining in these gray clouds - since Microsoft never made it into the Mobile/Tablet space, Webkit and Standards Based browsers defined the minimum standard for the Mobile Web.  No one wants IE on Mobile and luckily they shut themselves out of it before it ever even came up as an issue. I now spend most of my days building mobile web apps, luckily for me this means I can BLOCK any user agent that is based on "Trident/IE" and save myself countless days of development time. philip

  • Anonymous
    August 01, 2011
    The comment has been removed

  • Anonymous
    August 01, 2011
    @the_dees - well played on the politically correct neutral stance. I only have 1 question.  For which browser have you spent the most time dealing with bugs, missing or incomplete APIs etc. ? If you can honestly say any other browser than IE, then you are a very lucky developer. Very, very lucky.

  • Anonymous
    August 01, 2011
    @rebecca Thank you, if that was meant to be a compliment :) I just try to be fair. When you condem the many possible futures of someone or something only by judging their past, I think that just can't be right. The answer to your question depends greatly on the time frame you'd like me to examine. I'll overdo it a little and tell you that the Netscape Navigator was one of the most horrible browsers I have ever worked with. Microsoft was clearly superior at that time. That doesn't make me lucky though. I'm as unlucky as any other web developer out there. Though I don't think that's what really matters. Because my projects are local and small in scale, the IE issue is no more. My humble observation is that there is a new problematic kid on the block. Go to places where beginners discuss their problems. Usually you'll only find misunderstandings of floats or absolute position. But just the last week there camp up two entirely different issues and both were related to WebKit bugs. Yes, there are issues with other browsers and they come up as well every once in a while. But at the moment, WebKit issues are on top. I just try to make people aware of that. You're here, how many people have asked for Trident to be replaced by WebKit even though it's inferior by fact? I'd like people to think before they speak. It's more difficult than to cry out what the mass already cried out a hundred times, I know, since we all do it sometimes. But it's also well worth the effort. Sorry, got long, can't sleep. meh^^

  • Anonymous
    August 01, 2011
    HI , every body , can any one help me to rotate an image in ie using '-ms-transform:rotate(30deg);', it is not working in ie the help must be appretiated,

  • Anonymous
    August 01, 2011
    Thanks for the post. But... The Drag & Drop API is probably the most horrific thing I have seen as a web developer. It goes against any other event pattern in the DOM and ignores best practices. It's a dinosaur from the time when MS made a total mess of web development. And using it almost makes you cry. Seriously this API should be taken behind the shed and put out of its misery. You may want to have a look at what PPK from Quirksmode has to say about it: www.quirksmode.org/.../the_html5_drag.html Seriously, read it!

  • Anonymous
    August 02, 2011
    @the-dees, can you happen to click on "I can too" for the bugs reported by you on connect in order to vote 'em up? I did my part in voting there.. Also, I cannot find your contact (email) on http://the-dees.webs.com. I would like to submit some DOM & SVG related issues to your list and need little help for CSS2,3 & HTML,SVG for wikipedia. ~Keep coming the great work IE-team!

  • Anonymous
    August 02, 2011
    I don't understand... this means you have to manually set the draggable attribute to each tag I want to make draggable? why not make it a CSS property like user-select?

  • Anonymous
    August 02, 2011
    @Real McCoy : It seems I can, yes. Why are you asking?

  • Anonymous
    August 02, 2011
    he seems to be contributing to the wikipedia nonsense :D

  • Anonymous
    August 02, 2011
    @Real McCoy: I can click that text, yes. But it won't vote up any reports. The voting has been disabled after the rlease of IE8 IIRC. All reports are now rated equally. Generally, if you report an issue, make sure you have a minimal testcase (you can upload testcases when you zip them), detailed steps to reproduce and a good reason why fixing this bug would be important (interoperability can be a good reason). Having reported issues to all major vendors, I can tell you that is the most effective way to have bugs fixed. I noticed you have reported reports for SVG Filters, don't waste time with that. SVG Filters are to be re-specified and it won't make sense for IE to have them implemented at the moment. Instead, try to find issues in features already implemented. Many implementors often miss some details. Of course, there can be missing features (I've reported DOM XPath, which every other vendor implements), but these are mostly exeptions. Yeah, I don't have contact information available, but I don't understand how I might help you. The goal of 'my list' was to file bugs other people weren't able to report on Connect (which you are) or to file bugs that have been reported in the past, but were never reopened once they were closed unresolved. The list I maintain is mostly for myself to see what's left to do and to have an overview of what I have reported so far.

  • Anonymous
    August 02, 2011
    I am really looking to the good progress in IE development. At the same time, I really appreciate your effort on making it work in Enterprise environment. Though my company is using latest Microsoft technologies and a close partner, a bit skeptical about moving to IE9. It's would be helpful to see some posts addressing these issues.

  • Anonymous
    August 02, 2011
    I'm going to have to agree with PPK.  The drag and drop API is horrible, overly complicated and far from ideal. www.quirksmode.org/.../the_html5_drag.html Quote:"After spending about a day and a half in testing I am forced to conclude that the HTML5 drag and drop module is not just a disaster, it’s a !@#$ing disaster." (censored) I beg you to get together with other browser vendors from the W3C/WhatWG to come together and create a new API that is clear and simple for (a) Browser vendors to implement, and (b) for web developers to use. I'm not happy that Microsoft has already ruined HTML5 Video/Audio for the Web - but Drag-n-Drop has no patent/license issues that should cause incompatibility between browsers. Please, please, please re-consider this broken drag-n-drop API... ["Status Quo" has never, ever equated to "Best Design"] steve

  • Anonymous
    August 03, 2011
    The comment has been removed

  • Anonymous
    August 03, 2011
    yet another stunt from google's?

  • Anonymous
    August 04, 2011
    I don't get the move to making IE not cross platform? If Safari, Chrome, Firefox, and Opera all can have a cross platform web browser, why can't IE? And, for that matter, why should I, as a developer, care about the continuing progress of it if it's only for one version of Windows? Why should I spend time developing for it?

  • Anonymous
    August 04, 2011
    why should you, actually?

  • Anonymous
    August 04, 2011
    @Todd B., may be because that "one version of Windows" constitutes 27.92% of world's OS market share.. ref: www.netmarketshare.com/operating-system-market-share.aspx

  • Anonymous
    August 04, 2011
    @DanglingPointer And if IE actually adhered to standards, it wouldn't matter.. but, sadly, one has to spend way too much time trying to get something that should work to work in IE. It's just not worth it for a closed, single platform browser.

  • Anonymous
    August 04, 2011
    @Todd B., we are specifically talking about IE10pp2 here, don't we? Can you tell me the example where you have to spend "too much time" to work something on IE10pp2 as compared to FF6b? IE used to give lot of pain to the developers in past, I agree. But, the IE6 era is gone and IE is progressing, incorporating the set standards (SVG, CSS3, HTML5 etc.). If you are following the connect bug reports and their resolutions while running the various standards conformance tests, you might be agreeing with me. If you find any specific bug or issue yourself, please submit it to connect.microsoft.com. The next release of IE10 pp is scheduled in coming September. So logically, if IE10 is complying with and respecting the standards, it should make a developer or the user happy (rather getting mad!). Because not-respecting-the-standard was the only issue they had with IE which has been mitigated with the significant improvements and rapid development in IE.

  • Anonymous
    August 04, 2011
    The comment has been removed

  • Anonymous
    August 04, 2011
    MICROSOFT - Please fix this comment form! - If it wasn't for the awesome Firefox extensions that save my Textarea content for me I would have lost all of my message - AGAIN! It seems like there is a timer check on the backend that checks if you've taken more than 2 min to enter a comment and then if so, it ignores it.  For anyone that is trying to write up a full response it is massively annoying that the blog eats the comments. If there is no setting to fix/remove please consider getting off community server once and for all - the comment form has been an issue with this blog since day 1.

  • Anonymous
    August 05, 2011
    @DanglingPointer - I opened up a Connect ticket requesting the History API be supported in IE 10 (history.pushState, history.replaceState, window.onpopstate, etc): connect.microsoft.com/.../ie10-missing-html5-history-support-history-pushstate-history-replacestate-window-onpopstate I'm surprised it wasn't included in IE9 since the standard has already been adopted in all the other mainstream browsers.  Hopefully we'll get it in IE10.

  • Anonymous
    August 05, 2011
    Why is IE9 unable to save passwords on MANY sites even if password saving is enabled? Saving and autofill password in Neowin using IE. FAIL. Saving password on Hotmail sign in page using IE9. FAIL. Only Safari manages to save all passwords on all websites correctly.

  • Anonymous
    August 05, 2011
    hahaha, Safari wont even start if you have mandatory DEP/ASLR on ;(

  • Anonymous
    August 07, 2011
    Here is a bit inovation.... Noise in CSS – fo’ realz? bricss.net/.../noise-in-css-fo-realz

  • Anonymous
    August 07, 2011
    i don't use IE, because:

  1. IE saves pages slow.
  2. when IE is saving a page, browser is lock.