HTML and CSS Reference
In-Depth Information
<body>
<div id="publisherContent">
<div id="pubProduct" draggable="true" ondragstart="drag(event)"></div>
</div>
<div id="ad">
<div id="logo">Shopping Cart</div>
<div id="cta"> Drag Products To Drop Area! </div>
<div id="dropArea" ondrop=dropArea(event) ondragover=allowDrop(event)>
<div id="dropper"></div>
</div>
<div id="background"></div>
</div>
</body>
</html>
Hopefully you're following along in your favorite text editor. Now let's take a look at the code. First, we do some
basic ad set up and design using the CSS in the listing. Second, in the HTML we mimic having publisher content
(
publisherContent
) and dropping the mock products in our publisher page onto the ad area (
ad
). Next in our
publisherContent
div, there is a sample product,
pubProduct
, which has its attribute of
draggable
set to
true
and has
an event,
ondragstart
, to be handled with the function called
drag(event)
.
■
Note
You must pass in the “event” argument; otherwise the code will not function correctly.
Next, we put some more event handlers in the ad by leveraging the
ondrop
and
ondragover
events. These events
attach
dropArea(event)
and
allowDrop(event)
, respectively. Next, our functions get written using JavaScript. For
drag
we use a drag image with the method from the
dataTransfer
object by calling the method
setDragImage()
and
pass it three arguments. The first argument is the image asset, the second and third are the image's x and y coordinate
location—the place where the mouse will start the drag. This could be helpful if you want to create a custom image for
the element when the user is dragging.
Next, we tackle the
allowDrop
method, which signifies when the product can be dropped onto a content area. In
this case, we're using the entire ad as a drop zone.
■
By default, the
dragOver
and
dragEnter
events are not able to drop the element. You must explicitly cancel
these default browser actions by calling
event.preventDefault();
to drop an element.
Note
Last, once you know you're allowed to drop the product and once the user lets go of the mouse, that action
can be handled with the
dropArea
handler. Inside the
dropArea
method we grab the product's data by calling
the
dataTransfer
object again—but this time we retrieve the data by writing var data = event.dataTransfer.
getData(“Text”). Having the data object, we can then inject the data into the ad's real estate. The user now sees the
element inside the ad area, as Figure
6-1
demonstrates.