HTML5 Doctor » drag and drop http://html5doctor.com helping you implement HTML5 today Wed, 02 Mar 2016 08:08:54 +0000 en-US hourly 1 Drag and Drop and Automatically Send to the Server https://stevefaulkner.github.io/html5doctored/drag-and-drop-to-server/ https://stevefaulkner.github.io/html5doctored/drag-and-drop-to-server/#comments Tue, 03 Apr 2012 13:30:17 +0000 http://html5doctor.com/?p=4500 I realised (when looking myself) that there are a lot of demos and tutorials that show you how to drag-and-drop a file into the browser and then render it on the page. They're often labelled as "drag-and-drop and upload", but they actually don't upload. This tutorial will take you that final step.

]]>
I realised (when looking myself) that there are a lot of demos and tutorials that show you how to drag-and-drop a file into the browser and then render it on the page. They're often labelled as "drag-and-drop and upload", but they actually don't upload. This tutorial will take you that final step.

I'll walk you through an example that you can play with: drag a file into the web page, and it'll be uploaded to the server instantly.

Tasks

Let's break this process down into specific tasks:

  1. Capture the drop event and read its data.
  2. Post that binary data to the server.
  3. Provide feedback on the progress of the upload.
  4. Optionally render a preview of what's being uploaded and its status.

To achieve all of this, we need the following HTML5 and non-HTML5 APIs:

  1. Drag and Drop
  2. FormData
  3. XHR progress event
  4. FileReader

Keep in mind that not all browsers support all of this technology today, but they're getting close. I just wanted to create a clear and complete tutorial on how to go the whole hog and upload that dropped file.

The end result: we're able to drop the file anywhere in the browser, we get a preview and progress of the upload, and it's a slick experience.

Drag and drop upload
Our drag-and-drop example page

Drag and Drop

Just as a forewarning, drag-and-drop has been known to be a bit of a killjoy. In fact, it's a nightmare, but I won't repeat what's been said before.

Our example is going to allow you to drag-and-drop a file anywhere within the browser. To achieve that, we need to attach our event listeners to the body or documentElement (i.e., the root HTML node). By listening on the documentElement, this code could be anywhere in the page, as documentElement will always exist. You can only listen on body once the <body> element has been encountered.

Here's the pattern of code we need to capture the drop event on the entire document:

var doc = document.documentElement;
doc.ondragover = function () { this.className = 'hover'; return false; };
doc.ondragend = function () { this.className = ''; return false; };
doc.ondrop = function (event) {
  event.preventDefault && event.preventDefault();
  this.className = '';

  // now do something with:
  var files = event.dataTransfer.files;

  return false;
};
Basic pattern for capturing drop events

I'm using the hover class so that I can toggle a tip explaining to the user that the file can be dropped on the page.

Inside the drop event, we can access the dropped files via event.dataTransfer.files.

An Alternative to Drag and Drop

Annoyingly, as I write this, I realise this combination of API requirements is currently only met by Chrome and Firefox. So, taking the test from Modernizr, we can test for support and provide our alternative:

var dndSupported = function () {
  var div = document.createElement('div');
  return ('draggable' in div) || ('ondragstart' in div && 'ondrop' in div);
};

if (!dndSupported()) {
  // take alternative route
}
Testing for drag-and-drop support

Instead of drag-and-drop, we can insert a file input element (I've given it an id of "upload"), and when its value is changed, the file can be scooped in:

document.getElementById('upload').onchange = function (event) {
  // `this` refers to the element the event fired upon
  var files = this.files;
};
An alternative to native drag-and-drop

You can see the equivalent is simply the files property of the HTMLInputElement object. This will give us access to the same file as the event.dataTransfer.files from the drop event.

Automatically Uploading the File

This is the neat bit, and it's painfully simple. We use a feature of the XHR2 spec: FormData. Once we create an instance of FormData, we can append items to it:

var formData = new FormData();
for (var i = 0; i < files.length; i++) {
  formData.append('file', files[i]);
}

// now post a new XHR request
var xhr = new XMLHttpRequest();
xhr.open('POST', '/upload');
xhr.onload = function () {
  if (xhr.status === 200) {
    console.log('all done: ' + xhr.status);
  } else {
    console.log('Something went terribly wrong...');
  }
};

xhr.send(formData);
Creating and posting FormData

Yeah, that's it.†

Let's look at a couple of key things that are going on the above code.

formData.append('file', files[i]);

We're sending named parameters to our server, specifically an array of values called file. Obviously, you can call it what you want, but the file is the name your server will be looking for when it saves the uploaded file (or files).

xhr.onload = function () {
  if (xhr.status === 200) {
    console.log('all done: ' + xhr.status);
  } else {
    console.log('Something went terribly wrong...');
  }
};

If you're familiar with XHR, you'll notice we aren't listening to onreadystatechange, only onload — which is (in effect) a convenience function to let you know when the readyState is 4 (i.e., loaded!). You should still check and respond appropriately to the status code of the request to ensure it's 200 OK, rather than a 500 (internal server error) or 404 (not found) or anything else.

xhr.send(formData);

The nice trick here is that XHR has automatically set the encoding of the posted data to multipart/form-data. This encoding allows your server to read and save the files. It's like the encoding used when you send an attachment in an email.

Providing Feedback to the User

XHR2 now (flippin' finally) comes with a progress event. So if you're sending or retrieving a large file via XHR, you can tell the user how far along you are.

It's pretty simple. If you want to track the progress of the XHR request, listen to the progress event. One gotcha that caught me out for some time: I needed to track the progress of the upload, not the download. To do this properly, you need to listen for progress on the XHR upload object, as so:

xhr.upload.onprogress = function (event) {
  if (event.lengthComputable) {
    var complete = (event.loaded / event.total * 100 | 0);
    progress.value = progress.innerHTML = complete;
  }
};

xhr.onload = function () {
  // just in case we get stuck around 99%
  progress.value = progress.innerHTML = 100;
};
Providing feedback with XHR2's progress event

Note that instead of xhr.onprogress, we use xhr.upload.onprogess. When this event fires, we check that the event supports calculating the amount of data uploaded (the lengthComputable part), and then calculate the amount completed.

In my HTML, I'm using a <progress> element (similar to the <meter> element, but more semantically appropriate as we're presenting the progress of a task) to show the user how much of their file has been uploaded:

<progress id="progress" min="0" max="100" value="0">0</progress>

Note that I'm using innerHTML for browsers that don't yet support <progress>. Then with a dash of CSS-generated content, both the innerHTML and value of the progress can be the same (perhaps an over optimisation, but I was rather proud of myself at the time!).

And Finally, Rendering a Preview

As a nice addition, we'll give the user a preview of what we're uploading for them. It requires the File API — specifically the FileReader API.

As the drag-and-drop operation (or the input[type=file]) contains a file object, we can hand this over to the FileReader to get the contents of the file. If it's something like an image, we can get the Base64 data and give the user a preview. Or if it's text, we could render it in a <div>. The MIME type for the file is available as the type property on the file object.

So let's assume we only accept images. Here's the preview part that runs after the file has been received by the browser:

var acceptedTypes = {
  'image/png': true,
  'image/jpeg': true,
  'image/gif': true
};

if (acceptedTypes[file.type] === true) {
  var reader = new FileReader();
  reader.onload = function (event) {
    var image = new Image();
    image.src = event.target.result;
    image.width = 100; // a fake resize
    document.body.appendChild(image);
  };

  reader.readAsDataURL(file);
}
Rendering a preview of an uploaded image

We create the FileReader and give it a file to read. In the above example, I've used readAsDataURL, but you can also read files in plain text and binary formats (as per the spec).

When the reader has read the file and the data is available, it fires the load event, which in turn creates our new image.

The result of the file read action is in the event.target.result property. In the case of the readAsDataURL, the value is along the lines of data:image/png;base64,ABC....

Using All the Tools in the Shed

This example may be a little contrived for the article that I wanted to write. I've used many different technologies to do something that's a fairly common pattern on the web. In fact, it was because I had trouble finding a definitive source on uploading to the actual server (except, of course, as I wrote this article I found this example from back in late 2010!).

Hopefully, you'll see how each bit of tech can work together to create an application, but equally I hope that you can see where this would work if none or just some of the technology wasn't available. Make sure you detect functionality. Make sure you provide fallbacks. Make sure you develop responsibly.

Here's the final drag-and-drop and upload demo for you to play with.

Drag and Drop and Automatically Send to the Server originally appeared on HTML5 Doctor on April 3, 2012.

]]>
https://stevefaulkner.github.io/html5doctored/drag-and-drop-to-server/feed/ 41
Your Questions Answered 9 https://stevefaulkner.github.io/html5doctored/your-questions-answered-9/ https://stevefaulkner.github.io/html5doctored/your-questions-answered-9/#comments Fri, 14 May 2010 14:15:57 +0000 http://html5doctor.com/?p=1779 The Doctor is in with another round of patient questions about HTML5. This week, we'll cover offline viewing on requests, the drag-and-drop API, using href on any element, the <figure> element, and headings.

]]>
Doctor treating a patient illustration The Doctor is in with another round of patient questions about HTML5. This week, we’ll cover offline viewing on requests, the drag-and-drop API, using href on any element, the <figure> element, and headings.

Offline viewing on requests

Johan asked:

It is possible to let Firefox 3.5/3.6 save a page for offline viewing with the manifest file?
In that case Firefox asks for permission to save the site the same second you arrive – not very user-friendly.

Is it possible to send the save-it-locally request via Javascript on a click?

Basically I want a link/button which will fire the request – and not on document load.

While it isn’t possible to make Firefox 3.5/3.6 save a page for offline viewing with the manifest file, there is a way to do this. It all depends on how you write the “save-it-locally request” code. You have two options:

  1. If you want to store an arbitrary document that is not explicitly listed in your manifest, you could run an Ajax request for that document and store its contents in localStorage. When you want to view that document, load it from localStorage and overlay it on the existing page.
  2. Dynamically manage a manifest file for individual users, so that if a user requests a new file that isn’t in their manifest, register this on the server side and add it to the manifest — which is bespoke to this specific user — on the fly.

I’m not sure what you’re seeing with regards to the permissions error. When I test the manifest (offline **cache**), it doesn’t ask twice.

Note: you asked about Firefox 3.5 — the offline manifest doesn’t work properly at all in this version.

Thanks, Remy

Question about dragging

Marc asked:

Evening,

I’m trying to get my head around the drag and drop (DnD) possibilities of HTML5. I have a “simple” task: Read the content of a XML file, using JavaScript, and do some manipulations of he XML. Without the use of server side scripts.

I tried my way with Google, but apart from people complaining about the DnD specs, I wasn’t able to find much insightful informations.

Can you point me toward resources to understand the DnD possibilities of HTML5?

Thank you Doctor, a French canadian HTML5 fan ;)

Absolutely! There’s actually an HTML5 Doctor article covering native drag-and-drop. It also includes links for further reading and related posts (such as accessibility experiments).

I hope that helps.

Cheers, Remy

About the href on any element

Luan asked:

I’ve heard a long ago that href would work in any tag, such as a <p href="..."> or a h1, even a div and others… but I don’t see anything about this in the last days. Do you know if this is going to work?

That was in XHTML2 (on which the W3C have now stopped work).

The HTML5 equivalent is to wrap an <a href="..."> around the other tags. It’s called block-level linking, and we’ve written an article about it.

Cheers, Bruce

W3C Validator for the <figure> element

Fjpoblam asked:

I have a (prospective) structure containing 8 figures: each an image with a caption. My goal is an image gallery, each image clickable toward an individual htm file containing a slide show. (In html4 I structured each “figure” as a div: figure seemed ideal for the task.)

Problem is, I tried to follow the *validator* hint with a dd for the image and a dt for the caption (each surrounded by an a). Upon doing so, the validator pops up an error. When I try a straight image with a legend, it is also rejected for want of a dd and an optional dt.

What gives? Do you have a hint? Or better, simply, point me doofus to the correct doc so’s you’ll “teach a man to fish”.

I’m not sure if the validator is up to date or not, but you shouldn’t be using <dd>/<dt> in <figure> anymore. Please use <figcaption>.

See our article on the <figure> and <figcaption> elements for more.

Also see our glossary for more examples.

Cheers, Rich

Headings

Thomas asked:

Dear Doctors,

you covered the new header tag in an article. The header tag should contain a heading element, like h1-6. So far so good, but how do I structure my headings further on. E.g. I’ve got this:

<article>
	<header>
		<h1>My major heading</h1>
		<h2>Subheading</h2>
		Abstract text...
	</header>
	... lorem ipsum ....
	<hX>Heading within my article</hX>
	... dolor sit amet ...
	<hX+1>Subheading in my article</hX+1>
</article>

Which heading-level would be appropriate in my example? h1 because it starts again? or h3 because it continues?

Thank you

If the first <hX> is a new subheading and not related to the <h2> already there, then <hX> would be an <h2>. Then <hX+1> would be an <h3> if it is a subheading of the above <h2>.

However, if you’re splitting the article into sections, then you could use an <h1> each time. See our article on the section element for more.

Thanks, Tom

Got a question for us?

That wraps up this round of questions! If you’ve got a query about the HTML5 spec or how to implement it, you can get in touch with us and we’ll do our best to help.

Your Questions Answered 9 originally appeared on HTML5 Doctor on May 14, 2010.

]]>
https://stevefaulkner.github.io/html5doctored/your-questions-answered-9/feed/ 8
Why designers should care about HTML5 https://stevefaulkner.github.io/html5doctored/why-designers-should-care-about-html5/ https://stevefaulkner.github.io/html5doctored/why-designers-should-care-about-html5/#comments Wed, 14 Oct 2009 13:01:06 +0000 http://html5doctor.com/?p=973

Related Posts:

]]>
After a while on the fringes of our collective consciousness, HTML5 is finally getting the attention it deserves. The development community (as typified by the SuperFriends) has come together to debate practical elements of the spec, argue over the inclusion of controversial elements, and assess the timeframe over which we can unleash HTML5 in the wild.

However those of us more accustomed to the world of Post-Its, sketches, and .psds – the designers – haven’t been so vocal. Perhaps we’ve been distracted by the bright lights of CSS3 and those surface thrills we’ve longed for. (Rounded corners! Gradients! Transparency!) Or, alternatively, we’ve been in the thrall of @font-face and looking forward to the coming age of passable web typography.

Understandable. But it’s time designers got excited about HTML5 too.

Partly, it’s just good practice. Whatever your flavour of design – visual, web, interaction, user experience – knowing the native technology makes you better at your job. Just as composers should understand the capabilities of the orchestra’s instruments, designers need to understand the language of the web.

But there’s more to HTML5 than simply keeping our skills sharp. It could make a big difference to the way we design for the web.

Semantic elements

Information architects (and, by extension, user experience designers) should be excited by the new HTML5 elements – <nav>, <header>, <aside> and so on. While they won’t immediately revolutionise today’s web, they’re an investment for the future. Doing useful stuff with information is the central theme of IA, and therefore its practitioners should be at the forefront of the new experiences that machine-readable semantics will offer. HTML5 allows us to mark text up in a more meaningful way than a sea of <div>s, meaning we’ll soon see applications appearing at a sub-page level. We’ve started to scratch the surface – think about the Operator toolbar or customisable UIs à la iGoogle – but we’ll need detailed design thinking to work out how to bring the benefits of semantic richness to the end user.

APIs and other extensions

While it’s clear that some of the HTML5 APIs are far from perfect right now, when they’re refined they will offer us intriguing new opportunities and challenges.

Designers of location-based services should of course find the geolocation API invaluable. The contentEditable attribute gives us further power to make the web truly read/write without resorting to JavaScript and custom interfaces. New input types (eg type="search") can provide extra visual cues about input function, although of course this depends on the solutions chosen by the browser manufacturers.

Until now, it’s been easy to consider our domain as bounded by the viewport and the web server. But HTML5 is another step toward seamlessness: the merging of desktop, offline and online. For instance, the drag and drop API could see the line between online and desktop experience blur further. Local storage could allow for a web-like experience in areas of poor connectivity. This convergence is clearly a good thing, but we must also design how to expose those hidden seams at the user’s request. Users should stay in control of how their locations are published and what data is synchronised to their machine.

<video>, <audio>, <canvas>

There is of course something of a reported schism between the standards world and the Flash world. Some see the advent of these new media elements (particularly <canvas>) as heralding the death of Adobe’s poster child.

I don’t think this is either likely or desirable. Neither technology is perfect. Flash is, of course, proprietary and thus subject to the whims of a third party that stands between browser and user. <canvas> has known accessibility problems. But the two can live in harmony, if we play to their respective strengths. Some current Flash applications might be better suited to <canvas>, particularly those based around dynamic visualisation: graphs, animations, infographics. Some applications will benefit from the powerful capabilities of Flash: games, heavily interactive widgets.

This aside, there’s clearly a user experience benefit in not having to rely on an external plugin to play rich media elements, and it will be interesting to see the uptake of the <video> and <audio> elements. Although it will initially be down to browser makers to define the interface elements involved, we will need to figure out how to integrate them into everyday web experiences. The good news is that they can be styled in the same way as any other HTML element. If your visual aesthetic relies on slanted images with box shadows, it’s trivial to apply this to video too.

That said, we can’t ignore the elephant in the room: the thorny codec issue. I’m sure we’d all agree that the sooner it’s resolved, the better.

What can designers do?

Only the most patient and detail-oriented designer will relish the idea of reading the spec in full and arguing the finer points on the WHATWG list. That’s just not the way designers roll.

But as a community it’s important that we start talking about HTML5. If you’re new to HTML, now’s a great time to learn. The articles on this site and A preview of HTML5 give useful guidance on the differences between HTML5 and its predecessors. Above all, designers should get chatting with their developer friends: there can’t be many left who no longer have an opinion on this technology. How do they see their practices changing? What can we do today to prepare our sites for the advent of HTML5? How can we build on its strong points to make the web a better place?

We don’t yet know what we’ll accomplish with HTML5, but then it’s not often that the vocabulary of the web changes this deeply. However, one thing is clear: if we prepare now, we have a great chance to bring innovation to our users’ online lives.

This article was jointly published on Ineffable, Cennydd’s personal website.

Why designers should care about HTML5 originally appeared on HTML5 Doctor on October 14, 2009.

]]>
https://stevefaulkner.github.io/html5doctored/why-designers-should-care-about-html5/feed/ 16