Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Using drag and drop

From: HTML5 Power Workshop

Video: Using drag and drop

In this lesson I'm going to show you how to do drag and drop in HTML5. I'm going to drag several image files from my web publishing folder, Iinetpub www root onto one of these two canvases on my test web page. So, first of all, let me take one of these images, I'll take the Welsh flag, and I'll drag it and drop it over the fixed size canvas. So, as you can see, the canvas has accepted the file, and drawn it as an image, on the canvas. And the image, expands to fill the canvas size, in that first example. Now, see what happens when I drag the same image onto the second canvas. In this case, it actually draws the image in its real size, as opposed to expanding the image, to be the same size as the canvas was originally. To show you that, more vividly, I've got a picture here, of a ski run, called the Honey comb.

Using drag and drop

In this lesson I'm going to show you how to do drag and drop in HTML5. I'm going to drag several image files from my web publishing folder, Iinetpub www root onto one of these two canvases on my test web page. So, first of all, let me take one of these images, I'll take the Welsh flag, and I'll drag it and drop it over the fixed size canvas. So, as you can see, the canvas has accepted the file, and drawn it as an image, on the canvas. And the image, expands to fill the canvas size, in that first example. Now, see what happens when I drag the same image onto the second canvas. In this case, it actually draws the image in its real size, as opposed to expanding the image, to be the same size as the canvas was originally. To show you that, more vividly, I've got a picture here, of a ski run, called the Honey comb.

And I'll drag that first of all on to the first image. So, as you can see there, it's filled the canvas and if I do the same on the second one, now that's a bit more impressive. So, you can see that the image now has retained it's original size and the canvas has expanded to show it. I can only drag and drop, image files in this example. I've written some code which tests the mine type of the file that has been dropped. And if it's anything other than an image it will reject it.

So for example, I have a text file here, Hello World text. If I try to drag that and drop it onto a canvas. I get an error message to say, you should have dropped an image. Okay so let's see how that works. First of all the HTML file that's called dragdropfile.html. And it's in your Project Files folder. You need to copy that file plus any images you want to drag onto the web publishing folder. So, let's take a look at a code. I've opened it in my editor already, and I'll just take it to the bottom of the file first of all, so you can see what the actual page markup looks like. So, I have two canvasses here.

The first canvas, I've given it a class of fixed size. And the second one I've given a class of real size. And I test for that class when I drop a file onto the canvas to determine how exactly to shape it. So, when the window is loaded, this code executes. And this code gets all the canvas elements and sets up drag and drop event handlers for those canvas elements. So, we look through each canvas element and we handle the drag over event and the drop event on each canvas element.

So, this is how you can set up drag and drop support in HTML5. So, let's take a look, first of all, at the on drag over function to see what happens when you drag an item over the canvas. So this handler is here on line 22, and it's quite straightforward. All we do is to suppress the normal behavior of a drag and drop event. Okay, so I'm just preventing the default behavior of drag over. The interesting thing happens when the user lets go of the mouse to drop an item on the canvas. So here we have the on drop handler.

Let me show you the code for that. First of all I disabled default behavior of drag and drop. So, normally when you drop a file onto an HTML element, it will just display that on the web page replacing the file that was already there. I am suppressing that default behavior. I'm getting the target canvas, so depending on whether the user dropped onto the top canvas or the bottom canvas. We get that canvas, and then this is how you get the files, which have been dropped onto your element.

The most event object, which is passed in as a parameter. That event object has a data transfer property. And that will give you the list of files that have been transferred because theoretically you could drop many files onto a target. So what I do, I'm only interested in the first file that the user might have selected. So I get the first file. First of all then, we check whether there was a file and whether it's of the correct type. If it's of the incorrect type, like a text file, then we display an alert.

Otherwise, we use the HTML5 file reader API to read the image into memory. So let's take a look at this. I create a file reader object. When the file reader has completely finished It'll call that event handler. So, let me show you what happens here. I'm trying to read the file into memory. When that file's been completely loaded, this function will be invoked. And this function creates a new image element in HTML, and it sets the image element to be the file that's just been dragged and dropped.

And then it passes that image element into a function called Display image, which I'm going to finish off by showing you at the end of this demo. So, the Display image function takes an image element plus the target canvas, either the one on the top or the one on the bottom, in my example. So, let's take a look at the Display image function. It's quite straight forward really. The key point here is down the bottom, where I get the 2D context for the canvas and then draw the image.

So first of all we check whether the target canvas is the fixed size or not. If it has a class called fixed size, then we set the image and the height to be the same fixed size as the canvas itself. Othewise we resize the canvas so the canvas is now the same size as the image. And now once we've done that, we then draw the image on the 2D context for the canvas. So that's the end of this lesson. Key points.

In order to support drag and drop, you handle the drag over event and the drop event. In the drop event handler you will receive a mouse event. And the mose event has a data transfer property which gives you the files which have been dropped onto your target element.

Show transcript

This video is part of

Image for HTML5 Power Workshop
HTML5 Power Workshop

22 video lessons · 4034 viewers

Andy Olsen
Author

 

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Join now "Already a member? Log in

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed HTML5 Power Workshop.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.