HTML 5 Drag & Drop to Cart
Without any frameworks, demo with source code to drag its objects.
This demonstration offers to select an item in the store and transfer it to the basket... This allows you to see all the attributes and methods of the HTML 5 standard required to move elements to the page .
Compatibility: IE 9, Chrome, Firefox.
HTML 5 Drag and Drop Standard
The browser responds to every user action from the moment the object is pressed and holds down the mouse button until it releases the mouse:
- Take an object to the page: press and hold the button .
- Move object to page.
- Release the mouse button. If this is done in the area to be moved, the object is physically copied or moved to the page.
This involves adding event handlers to the two items involved: the item being moved and the area where it can be moved. The specification defines a list of events and attributes to be assigned to page elements...
New HTML Attributes
- draggable
- The draggable =" true" property indicates that the HTML element can be moved to the page. It is useless for some items that can be moved by default, such as images. In the basket example, we move images.
- dated standing each other
- The value of this attribute is used to describe the object that can be moved. It will be used by event handlers if they want to use object-specific processing.
- to the drop zone
- The attribute of the container where the object can be placed. The value of this attribute is not "true," but varies depending on the permissions granted. To accept a PNG image file, the value is "file: image/png." For text, it will be "string: text." Other parameters can be included in the value. For example, a move value is added.
dataTransfer object
This is the interface for the object currently being moved to a page that JavaScript code can use. She has attributes:
- DOMString dropEffect A
- user-initiated move is assigned the operation type copy to copy, move to move, link to add a reference to the inital element, or none to delete. This is assigned when the dragstart event is triggered .
- DOMString effectAllowed.
- An operation type is assigned that is valid for the user when the object enters the destination area, so when dragover and dragover events are triggered. The assignment is performed when the user enters an object to move, that is, in the function associated with the dragstart event. The previous types of operations are added "copyLink," "copyMove," "linkMove," "all" and "unitialized" (see the specification for their use).
- DataTransferItemList Items
- This list is associated with any dataTransfer object. Read-only, it allows you to return a list of moved items. It has a length attribute, an items attribute and methods clear (), add (DOMString data, DOMString type), add (File data), as well as the delete command, which allows you to delete an item from the list to a specified index.
And the interface has the following methods:
- setDragImage (image element, x, y )
- To assign an image to a moving object by replacing the image you enter.
Note: dataTransfer has methods other than specification, but are non-standard, so they are not repeated here.
New developments
The names in this list are used as if with the EventListener add-in or before "on" to be used as an attribute of any HTML tag.
Each object that can be moved has two events associated with it.
- dragstart
- This event is assigned a function that contains processing when the user initiates a move.
- dracend
- This event is associated with an object that can be moved to respond to the end of the move. Unlike drop, it works even when an object leaves the destination zone, so in our example it leaves the recycle bin.
And four events concern the goal.
- dragenter
- This event is raised when an object hits the surface of the target container.
- dragover
- This event is added to the container tag. It is triggered when the mouse hovers.
- dragleave
- It works when you release an object that you move. If there are multiple targets on a page, it works when you leave one target to hit another.
- tracks
- This event is raised when the user releases an object on the surface of the container tag.
Example of standard code
The store in our example contains four objects:
<fieldset id="shop" class="shop"> <legend>La boutique</legend> <img class="product" id="chaise" src="image/chaise.jpg" width="96" height="96"> <img class="product" id="moniteur" src="image/screen.jpg" width="96" height="96"> <img class="product" id="valise" src="image/valise.jpg" width="96" height="96"> <img class="product" id="transat" src="image/transat.jpg" width="96" height="96"> </fieldset>
You need to know that since our objects are images, they move by default. If we are talking about other elements, you need to add a statically stretchable attribute, as shown below, or dynamically in JavaScript, as the code does below:
<div class="product" draggable="true"> <img src="images/chaise.jpg" width="96" height="96"> </div>
The user recycle bin can be any type of container tag. Since a fieldset containing the legendary tag is used, a layer is added to it to initially have an empty container:
<fieldset id="mycart" class="cart"><legend>Mon panier</legend> <div id="cartArea"></div> </fieldset>
Here is the full JavaScript code, which we will explain below:
<script> var cartArea = document.querySelector('#cartArea'); var prods = document.querySelectorAll('.product'); for(var i = 0; i < prods.length; i++) { prods[i].setAttribute('draggable', 'true'); // optionnel avec des images prods[i].addEventListener('dragstart', function(evnt) { this.className = 'itemchoosen'; evnt.dataTransfer.effectAllowed = 'copy'; evnt.dataTransfer.setData('text', this.id); return false; }, false); } cartArea.addEventListener('dragover', function(evnt) { if (evnt.preventDefault) evnt.preventDefault(); evnt.dataTransfer.dropEffect = 'copy'; return false; }, false); cartArea.addEventListener('dragenter', function(evnt) { return false; }, false); cartArea.addEventListener('dragleave', function(evnt) { return false; }, false); cartArea.addEventListener('drop', function(evnt) { if (evnt.stopPropagation) evnt.stopPropagation(); var id = evnt.dataTransfer.getData('text'); var theitem = document.getElementById(id); // theitem.parentNode.removeChild(theitem); // une option non retenue ici theitem.className='itemblurred'; var y = document.createElement('img'); y.src = theitem.src; cartArea.appendChild(y); evnt.preventDefault(); // pour Firefox return false; }, false); </script>
Code Information
The HTML objects of the products are listed using the querySelectorAll method. This is one of the options. The dragggable property is then added to each tag representing the product as a demonstration (this works without because you move images). Each tag is then associated with a dragstart event and a function that responds to that event.
In our example, when you initiate page navigation, the product image becomes a red box.
The content to be transferred is defined by dataTransfer.setData. It has a text type and tag ID representing the product.
var prods = document.querySelectorAll('.product'); for(var i = 0; i < prods.length; i++) { prods[i].setAttribute('draggable', 'true'); // optionnel avec des images prods[i].addEventListener('dragstart', function(evnt) { this.className = 'itemchoosen'; evnt.dataTransfer.effectAllowed = 'copy'; evnt.dataTransfer.setData('text', this.id); return false; }, false); }
We associate the dragEnter and dragLeave events with the tag where we want to remove objects. In our example, no treatment is added.
We're also tying dragOver. This is an opportunity to assign an effect .
cartArea.addEventListener('dragover', function(evnt) { if (evnt.preventDefault) evnt.preventDefault(); evnt.dataTransfer.dropEffect = 'copy'; return false; }, false);
Finally, a drop event is added that allows you to assign processing to be performed when an object is placed in the trash.
cartArea.addEventListener('drop', function(evnt) { if (evnt.stopPropagation) evnt.stopPropagation(); var id = evnt.dataTransfer.getData('text'); var theitem = document.getElementById(id); // theitem.parentNode.removeChild(theitem); theitem.className='itemblurred'; var y = document.createElement('img'); y.src = theitem.src; cartArea.appendChild(y); evnt.preventDefault(); // for Firefox return false; }, false);
This is the most complex function (in our example) and the most important, so it deserves detail.
- Calling stopPropagation does not trigger events that may occur because we are changing on the page.
- Retrieves the dataTransfer content with the product ID.
- This allows you to place the corresponding HTML element in the theitem variable. On
- At this point, you can remove the object from the vault using the removeChild DOM method. This would be good for some procedures when it comes to moving objects to the page, but not for our example, so I added this instruction as a comment.
- To insert an image into the recycle bin, you create an image tag, assign the moved object tag as the source, and add the tag as a child of the cartArea container.
- Default events are canceled using preventDefault. This is necessary for Firefox.
This treatment is a demonstration. You can return to the code structure and associate different processing with events, depending on which application should be implemented. In the case of an online store, items added to the cart are not removed from the original list, since you can add several to the cart. In other cases, the movement is material, the object is removed at one point to be placed at another.
The CSS code is also specific to our example and answers the choice. This can be seen from the source on the demo page .
This demo page provides easier access to JavaScript and CSS source code. Its use is absolutely free (with the exception of a textbook on the network).
Links
- The icons used for this demo were offered for free by Getty yicons. (Shift 06/2014: site now closed). In
- the WHATWG Drag and Drop specification describes the standard .