MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to drag and drop an object using html5

In this article, we will learn what is DnD api of html5 and why do we use it. Also we will see how can we write a code to drag and drop an object from one location to another in html5.

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

It’s initially been a long time to work with javascript complex code or jquery library or dojo library to make enable designing objects like rounding corners, dragging objects into the html pages. It was the time of working with html4. Now in the era of working html5, there is an api provided by html5 to work with such kind of complex task that make it very easy to acquire.

HTML5 DnD api in detail:

DnD html5 api is very powerful to work with html objects to drag, re-position, and delete them using mouse events. Using this api, user will be able to re-position or update a html view, once a user click and hold an object to drag from one to another location or remove from the view.

HTML5 is being supported all popular web browsers like Firefox, Safari, Internet Explorer, Opera, Chrome and etc.

There a set of events, which are called to handle drag and drop events, which are listed below:

Events Description
drag This event is fired, while a mouse cursor is moved. It is responsible to view the dragging of an object from one location to another.
drop This event is fired, while a drop or mouse button is clicked out and dropped. This event listener is responsible for the dragging all the information from last location to this dragged location and display it.
dragstart This event is responsible start dragging of an object.
dragenter This event is occurred right before starting a dragging an object. It is responsible to estimate, if an object is available for dragging or not.
dragover This event is occurred, while a mouse is moved over an object or element. It is sometimes called at the same time while dragenter is occurred.
dragend This events fires, while user releases mouse button after dragging an object.
dragleave This event is occurred, while an object is released from mouse. It is responsible for to remove highlight of dropped location.

Table 1: Dragging Events

Table 1 shows a list of dragging events to work on that helps to manage dragging of any html5 object or events.

To create a dragable content, we are required to set draggable attribute to true. We may place this attribute to any element that wish to be made draggable.

Listing 1: Draggable example

<div id="row">
  <div class="col" draggable="true"><header>AA</header></div>
  <div class="col" draggable="true"><header>BB</header></div>
  <div class="col" draggable="true"><header>CC</header></div>
</div>

Listing 1 define a div with id “row” and its three sub-divs with class “clol” that support draggable property of html5. The sub-div has header tag.

Now before setting up dragging functionality, lets set up the icon that make sense to draggable property. This can be achieved using cursor style property to “move” As shown in listing 2:

Listing 2: style for the document

<style>
	.col{
		 border: 2px solid green;
		  background-color: #ccc;
		  margin-right: 25px;
		  -webkit-border-radius: 5px;
		  -ms-border-radius: 5px;
		  -moz-border-radius: 5px;
		  border-radius: 5px;
		  text-align: center;
		  cursor: move;
		  height: 150px;
		  width: 150px;
		  float: left;
	}
	#row{
		border:1px dotted;
		height:200px;
		width:550px;
		padding-left:35PX;
		padding-top:35PX;
	}
</style>

Listing 2 defines style properties for created divs. It defines cursor properties to “move” and few other styling properties applied to column divs as shown in Figure 1:

displaying three columns with the dragging activated

Figure 1: Displaying three columns with the dragging activated

To start dragging a column, we are required work on drag events as listed in Listing 1. Let’s start working with the dragstart drag event. This event will setup the opacity to 50%, while it start dragging a column out of these three columns.

Listing 3: dragstart event

function dragStart(e) {
  this.style.opacity = '0.4'
}
var cols = document.querySelectorAll('#columns .column');
[].forEach.call(cols, function(col) {
  col.addEventListener('dragstart', dragStart, false);
});

Listing 3 define the dragstart event, where dragStart() method setup the opacity of the dragging column to 50%. This method is added to Event Listener with these all three columns. This functionality is shown into the figure 2 as below:

column 2 starts dragging

Figure 2: column 2 starts dragging

Figure 2 shows that column “BB” was started dragging. Its opacity was reduced to 50%, while it was started dragging.

Now, let’s define events dragenter, dragover, and dragleave in listing 4 as below:

Listing 4: dragenter, dragover and dragleave events

function doDragStart(e) {
  this.style.opacity = '0.4';
  return true;
}

function doDragOver(e) {
  if (e.preventDefault) {
    e.preventDefault();
  }
  e.dataTransfer.dropEffect = 'move';
  return false;
}

function doDragEnter(e) {
  this.classList.add('over');
}

function doDragLeave(e) {
  this.classList.remove('over');
}

var cols = document.querySelectorAll('#row .col');
[].forEach.call(cols, function(col) {
  col.addEventListener('dragstart', doDragStart, false);
  col.addEventListener('dragenter', doDragEnter, false);
  col.addEventListener('dragover',  doDragOver, false);
  col.addEventListener('dragleave', doDragLeave, false);
});

Listing 4 define four methods doDragStart(), doDragOver(), doDragEnter() and doDragLeave() and these methods are applied to these columns using forEam looping structure.

We can also replace one div to another div position and vice-versa. In this way, it need to hold of piece of data of dragging div and of the div, on which it is moving on. Data transfer is done in dragstart event and reading of data is handled into the dragdrop event.

Calling of e.dataqTransfer.setData(format, data) is used to set the object’s content to mimetype object that can be moved out easily. To get the data from mimetype object which was set, while calling dragstart event, getData(format) method is called. This method process the data retrieving from mimetype as shown in listing 5:

Lisitng 5: transfer data

var transferElement = null;

function handleDragStart(e) {
  // Target (this) element is the source node.
  this.style.opacity = '0.4';

  transferElement = this;

  e.dataTransfer.effectAllowed = 'move';
  e.dataTransfer.setData('text/html', this.innerHTML);
}
function handleDrop(e) {
  // this/e.target is current target element.

  if (e.stopPropagation) {
    e.stopPropagation();
  }

  if (transferElement != this) {
    transferElement.innerHTML = this.innerHTML;
    this.innerHTML = e.dataTransfer.getData('text/html');
  }

  return false;
}

Now let’s go through with the live example that creates two divs and move one div to another div as shown into the Listing 6:

Listing 6: Dustbin Example

<!DOCTYPE HTML>
<html>
<head>
	<style type="text/css">
		#moveto, #movein {
		   float:left;
		   padding:10px;
		   margin:10px;
		   -moz-user-select:none;
		}
		#moveto {
			background-color: #ccc;
			margin-right: 25px;
			-webkit-border-radius: 5px;
			-ms-border-radius: 5px;
			-moz-border-radius: 5px;
			border-radius: 5px;
			text-align: center;
			cursor: move;
			height: 100px;
			width: 110px;
		}
		#movein {
			background-color: green;
			margin-right: 25px;
			-webkit-border-radius: 5px;
			-ms-border-radius: 5px;
			-moz-border-radius: 5px;
			border-radius: 5px;
			text-align: center;
			cursor: move; width:150px; height:150px; 
		}
	</style>
	<script type="text/javascript">
		function dragStart(ev) {
		   ev.dataTransfer.effectAllowed='move';
		   ev.dataTransfer.setData("Text", ev.target.getAttribute('id'));
		   ev.dataTransfer.setDragImage(ev.target,0,0);
		   return true;
		}
		function dragEnter(ev) {
		   event.preventDefault();
		   return true;
		}
		function dragOver(ev) {
			return false;
		}
		function dragDrop(ev) {
		   var src = ev.dataTransfer.getData("Text");
		   ev.target.appendChild(document.getElementById(src));
		   ev.stopPropagation();
		   return false;
		}
	</script>
</head>
<body>
	<center>
		<div id="moveto" draggable="true" 
			 ondragstart="return dragStart(event)">
		   <p>Move Me</p>
		</div>
		<div id="movein" ondragenter="return dragEnter(event)" 
			 ondrop="return dragDrop(event)" 
			 ondragover="return dragOver(event)">
			<b>Dustbin</b>
		</div>
	</center>
</body>
</html>

Listing 6 defines a code that defines two divs “moveto” and “movein”. First line of the listing defines the document type that defines html type document. Next, tag is defined into the <html> <head> tag. It defines two ids type properties for “#moveto” and “movein” ids. Next <script> tag defines dragStart(), dragEnter(), dragOver() and dragDrop() methods that defines the way to move “movein” div into “moveto” div. Next, tag <body> defines <center> tag with two <div> tags with id names “moveto” and “movein” ids. “moveto” id represent “Move To” string and “movein” id represent “Dustbin” string.

Move Me and Dustbin

Figure 3: Move Me and Dustbin

Figure 3 shows two divs “Move Me” and “Dustbin”. “Move Me” will be moved to “Dustbin” div. Figure 4 shows “Dustbin” that holds “Move Me” div into itself after dragging “Move Me” onto “Dustbin” div.

Move Me div moved into Dustbin div

Figure 4: Move Me div moved into Dustbin div

Figure 4 shows “Move Me” div moved to “Dustbin” div.

Conclusion

In this article, we learn about html5 drag and drop api that helps to transfer html elements and attributes moving form one location to another location and also learn the ways of working dragging events.



Software developer with more than 5 years of development on Java, HTML, CSS.

What did you think of this post?

Did you like the post?

Help us to keep publishing good contents like this.

SUPPORT US

funded

remaining

[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually � in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits � in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login