Nov 09, 2015
When a user interacts with our applications, being either a website or an Office Application; we need to add functionality that can improve the user’s experience. This can be a variety of things, such as data validation and interaction with objects on the site.
Adding functionality such as drag and drop can simplify the interaction between your application and the user, an example of this could be a user that wants to add a product to a shopping cart by just dragging the image into the shopping cart.
Here is a simple list of steps so you can implement this API yourself:
Create a page that you want to use the functionality on. In this demo I have created an HTML page with four items on it; these items will be used for dragging and will be dropped onto a container to capture the items information.
Here is the markup code of the HTML body:
The needed parts for the body are:
- Must contain an element that you want to drag, in my case an Article with a class of “Darticle” (in Green).
- These elements must contain information you want to capture in the drop zone, in my case I am capturing the “id” and “data-description” attributes (in Purple).
- The rest of the nested elements are just used for display purposes.
- Must contain a “drop Zone” where the information needs to be copied to.
In this file. we create a function to add the Drag and drop actions all at once, called “InsertDndAction”. Within this function we add three variables:
- A collection of our draggable items called “Dragimages”.
- An object to represent our DropZone, called “Dropzone”.
- An object to represent the “ul” element in the dropzone that will be used to drop items into. This is called “TheDropzone”.
Next, we add functionality so that all the images within the “Dragimages” collection can listen for when it is being dragged. Within this loop we add an event listener to each item that looks for the “dragstart” event. When that event fires we execute a function that copies the data and sets the “Text” value equal to the Item’s ID.
The following piece of code adds two events to the Dropzone, one called “dragover” and another called “drop”. The dragover event will trigger once the users drag an object into the dropzone and the drop event will trigger once the user lets go.
In the dragover event we just want to allow the user to copy data.
In the drop event we get the value of the “Text” key set earlier in the “dragstart” event, and get the corresponding element on the page with the same ID. We then call the following method to add a new item to the “ul” in the “Dropzone”.
In this method we set a variable equal to the “id” and “data-description” attributes of the dragged item. We then create an object to be added to the list inside the dropzone.
The final product will look like the following: