HTML5: Drag and Drop in Depth
Illustration by John Hersey

Exploring the RPS code


From:

HTML5: Drag and Drop in Depth

with Bill Weinman

Start your free trial now, and begin learning software, business and creative skills—anytime, anywhere—with video instruction from recognized industry experts.

Start Your Free Trial Now

Video: Exploring the RPS code

So let's take a look at the code for a Rock Paper Scissors application. Here it is. It's called RPS.html and you'll find it in the Chapter 3 folder in your exercise files. I'm just going to scroll down here and I'll scroll slowly so that you can watch. I'm just going to scroll down here to the bottom and we're going to start with the HTML part and then we'll work our the way through the JavaScript. So here in the HTML you'll notice that we have the status message, which is the id is statusMessage and the class is message, and that gives us this nice brown area here at the top that has the words Using HTML5 drag and drop, and that's where we get all of the statuses. As I pick up an image, it says dragging and hovering and whether something wins or not.
please wait ...
Watch the Online Video Course HTML5: Drag and Drop in Depth
1h 0m Intermediate Jul 26, 2011

Viewers: in countries Watching now:

Join Bill Weinman as he shows how to make just about any web page element draggable with a combination of JavaScript and HTML5, a technique that has increased browser support and that eliminates the need for external libraries such as jQuery. The course covers how to detect drag-and-drop support in the user's browser, code a simple event listener, use a drop zone, and even receive dropped objects without a drop zone. A simple working example game, a practical implementation of drag-and-drop that can be applied to almost any web site, is also demonstrated.

Topics include:
  • Exploring the HTML/Javascript/CSS/DOM relationship
  • Detecting drag and drop support
  • Using the HTML5 draggable and dropzone attributes and onDragStart event
  • Exploring different events
  • Receiving drops with or without a drop zone
  • Creating a simple game
Subjects:
Developer Web
Software:
HTML
Author:
Bill Weinman

Exploring the RPS code

So let's take a look at the code for a Rock Paper Scissors application. Here it is. It's called RPS.html and you'll find it in the Chapter 3 folder in your exercise files. I'm just going to scroll down here and I'll scroll slowly so that you can watch. I'm just going to scroll down here to the bottom and we're going to start with the HTML part and then we'll work our the way through the JavaScript. So here in the HTML you'll notice that we have the status message, which is the id is statusMessage and the class is message, and that gives us this nice brown area here at the top that has the words Using HTML5 drag and drop, and that's where we get all of the statuses. As I pick up an image, it says dragging and hovering and whether something wins or not.

And that's all in that statusMessage, so that's what that looks like in the HTML. And then we have the div id equals columns and that's simply a container for the three images and their captions. Each of the images and caption sets are wrapped in a div of class rps, which stands for rock, paper, scissors, and they have IDs of rps1, rps2, and rps3, and this allows him to be identified for purposes of the drag-and-drop. You'll notice that the image itself is set to draggable. You know in a lot of browsers everything is draggable anyway, but that shows the intent that something is going to grab the image and not the container itself.

So I'm going to grab this image and you see that the image kind of detaches itself from the div and I'm not dragging the caption around. I'm just dragging the image around. And we are using the HTML5 tag footer for the captions at the bottom of each of the divs and you'll see that there are the word paper, word scissors, the word rock there on screen. In the JavaScript under App lifetime support, the window.onload function, this is just my personal preference over having an onload attribute for the body tag.

It forces the application to wait until the entire page is loaded from the server before it goes and calls the initialize function. This make sure that all of our variables exist, that all of our elements exist, and it prevents a whole lot of strain and hard to debug errors from happening, and so always do that and always stick get it at the very bottom. And then that calls the init function and the init function tests to see if drag-and-drop is supported and if it is, it goes ahead and does all of the initialization. If it's not, it displays a statusMessage. It says this browser does not support drag-and-drop.

And you can see that in action if I try to load this up in Opera and I will go ahead and do that. And you see the message there, This browser does not support Drag and Drop. Once we've detected the drag and drop, we go ahead and display the status message that says that we're using it. Then we take this dndEls -- that's the drag-and-drop elements array -- and you'll notice that that's initialized way up here at the top with new Array right there.

And we simply push the three div elements on there and so that's our rps1, rps2, and rps3. That's these three divs down here. And so that gets pushed onto that array, and then we step through the array and for each element in the array we resister each of our event listeners. So this is simply a shortcut, so I don't have to have to have 18 calls. Instead I have just the six calls to event listener. It just makes the code a little bit easier to read. And so I'm registering all of our event listeners, dragstart, dragend, dragover, dragenter, dragleave, and dragdrop, and we're actually using all of those.

Here under Utility functions this is just stuff that I pulled out of the library that we use here. So I don't have to pull in the library with a lot of stuff that we're not using. And that's just for displaying status message and for calling document getElementById. My shortcut for that just called Element, that I tend to use. We'll get back to these utility functions and I want to go right into the event handlers here. We'll start with the handleDragStart. When we call DragStart we set the dragging element, which is a global variable, to this.

This, inside of each of these event handlers, this is always the element itself that is being operated upon. And so in the case of DragStart it is the image that you've grabbed drag. So if I come in here to the browser and I grab this rock, then DragStart now has the whole rock div, because you'll remember that's the element that got registered down here in init. We add listeners to all of the divs, rps1, rps2, rps3, those are the outer divs, and so that's what the listeners listening to and that's what it gets passed in when we call DragStart.

So I set its class to moving and that's what allows the CSS3 magic to happen, because that is part of the class moving. And we set its opacity and we set the hoverBorderStyle and so the hoverBorderStyle is the one with the dashes, and so you remember when you do the hover, but we're also using it here just because it seems to work nicely there. And then we set the DragImage and the DragImage is actually part of this dataTransfer object. We don't use the dataTransfer object for anything else, but to set the DragImage, and the DragImage is simply the image from this, so it calls getRPSImg which is of our utility functions.

You notice the getRPSImg it goes into the object. It steps role over the children, it looks for the one that has the element name image, and it returns that. And then it sets that image to the DragImage. And so what it is doing, it goes through, it grabs the image itself, and it set to its DragImage. You'll notice that even if I grabbed this up in the corner here, it always sets my cursor to the middle because here I'm setting it 120 and 120 and these are 140 pixel wide and 140 pixel tall images.

So that's our DragStart. It sets up our styles and it saves a way the draggingElements so that we can use that throughout the rest of the cycle. And then all of the border styles get reset when we call DragEnd and all of the class names get reset, so this is basically just resetting everything with DragEnd. The opacity gets set back to 1.0, and so anytime we let go of something, no matter where we let go of it everything gets reset.

DragOver is actually doing two things. It's doing the preventDefault thing that allows the drop to work and it sets the border style to the hoverBorderStyle. And if you remember the hoverBorderStyle has these gray dashed lines and the normal border style is a white border so that it takes up the same amount of space, but it is effectively invisible against the white background. DragEnter sets the hoverBorderStyle for the object that is being hovered over and it sets this statusMessage that says hoverDraggingElement over the type for this.

And so getRPSType works like this. Just like getRPSimg stepped through looking for an image, getRPSType calls getRPSFooter which steps through and gets the footer element and then grabs the innerHTML from that footer element. And so the innerHTML of course is the type. It's Rock, Paper, Scissors. So this footer is serving two purposes. One purpose is it displays this text at the bottom and the other purpose is it identifies the type and so we're using it for both of those purposes.

DragLeave simply resets the border style, and then handleDrop does the magic. You notice it does stoppPropagation and preventDefault. This prevents browsers from doing weird things, and unfortunately this is just part of working with HTML5 drag and drop, is different browsers have different default actions and do different weird things, and sometimes you just need to prevent them from doing that. And then it checks using the triple equals sign, which in JavaScript is for identify a quality rather then value a quality, and it checks if this is the same as the draggingElement.

If it is, then you're dropping something on itself and you don't want to do anything, so we simply return. Otherwise we call isWinner and when we call isWinner, isWinner gets this and the draggingElement, which is the under and over, and it checks for the types of them, it indexes into the winner's hash, and it decides what beats what. And if it wins, then it call swapRPS and if it doesn't win then it doesn't win call swapRPS, and then swapRPS is very simple. It's a few lines of code and it's really very simple.

It simply takes the A object and stores all its values in a holding tank and then it replaces them with the values from the B object. And then it replaces the B object with the stuff that had been saved. And so it's really very simple and it simply takes A and copies it over to B and takes B and copies it over to A and you end up with this nice little swap happening, when your images get swapped.

So that's really it. That is pretty much the entire application. Like I said it's roughly 200 lines of JavaScript, but even though it's that much code it's still fairly simple and this is a really good simple clear example of how to implement HTML5 drag and drop and its event model into a fairly complete application. So feel free to use this code as a starting point for your own applications.

There are currently no FAQs about HTML5: Drag and Drop in Depth.

 
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

* Estimated file size

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: Drag and Drop in Depth.

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 ?

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 preferences from 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.

Learn more, save more. Upgrade today!

Get our Annual Premium Membership at our best savings yet.

Upgrade to our Annual Premium Membership today and get even more value from your lynda.com subscription:

“In a way, I feel like you are rooting for me. Like you are really invested in my experience, and want me to get as much out of these courses as possible this is the best place to start on your journey to learning new material.”— Nadine H.

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.