HTML5 Drag and Drop Tutorial

Drag and drop functionality is usually implemented using a JavaScript or jQuery plugin. That is generally a good solution. However, when extensive customization is needed, native HTML5 drag and drop is a better choice. Native HTML5 drag and drop is also faster and more responsive solution. Read this tutorial to find out how to implement the native drag and drop functionality in just a few minutes.

Draggable Content

First, we need to create the HTML markup for draggable content:

  • Column content 1
  • Column content 2
  • Column content 3

This is a simple unordered list with 3 items. Not all HTML elements are draggable by default, but that can be changed with the following CSS code:

 [draggable] {  -moz-user-select: none;  -khtml-user-select: none;  -webkit-user-select: none;  user-select: none;  /* Required to make elements draggable in old WebKit */  -khtml-user-drag: element;  -webkit-user-drag: element;}. list_column {  cursor: move; }

At this point, the list items can be dragged, but cannot change positions. To create that, we will need to implement the event listeners.

Event Listeners

There are six events that we need to implement in order to have the native drag and drop functionality:

  • dragstart
  • dragenter
  • dragleave
  • dragover
  • drop
  • dragend

So, let’s start the drag with dragstart event:

// This variable will hold the dragged item objectvar dragSrcEl = null;$('.list').on('dragstart','.list_column', function(e) {		e.stopPropagation();		// Add the CSS class to the element that is being dragged	// This allows to style that element	$(this).addClass('dragging');		dragSrcEl = this;	// Set data transfer object values	e.originalEvent.dataTransfer.effectAllowed = 'move';	e.originalEvent.dataTransfer.setData('text/html', $(this).html());	});

The dragged element can be dropped on any other list item (let’s call it the drop zone). Dragenter defines what happens when the dragged element enters the zone where it can be dropped:

$('.list').on('dragenter','.list_column ', function(e) {	  	  // Add the CSS class to the drop zone  // That way we can indicate the drop location to the user	  $('.list_column').removeClass('over');	  $(this). addClass('over');});

When the element leaves the drop zone, the dragleave event is fired:

$('.list').on('dragleave','.list_column', function(e) {	// Element is not a drop zone anymore – remove the CSS class$(this).removeClass('over');});

The dragover event is triggered while the dragged element is in the drop zone:

$('.list').on('dragover','.list_column', function(e) {	// Prevent the default browser behavior	if (e.preventDefault) {		    		e.preventDefault();  	}	e.originalEvent.dataTransfer.dropEffect = 'move';	return false;	});

When the dragging has stopped, we need to clean up the assigned CSS classes used for styling the element being dragged and the drop zones:

$('.list').on('dragend','.list_column', function(e) {	// Remove over and dragging CSS classes  	$(this).removeClass('dragging');	$('.list_column').removeClass('over');});

The event that contains most of the HTML5 drag and drop logic is the drop event, which is fired after the user drops the element (releases the mouse button):

$('.list').on('drop','.list_column', function(e) {	// Remove over and dragging CSS classes  	$(this).removeClass('dragging');	$('.list_column').removeClass('over');	// Stops the browser from redirecting	if (e.stopPropagation) {    		e.stopPropagation();	}  	// Do the drop only if the dragged item and the drop zone are not the same elements	if (dragSrcEl != this) {    		// Set the dragged element HTML to the HTML of the item we have dropped on.		$(dragSrcEl).html($(this).html());		$(this).html(e.originalEvent.dataTransfer.getData('text/html'));    	}	return false;	});

Basically, when the dragged element is dropped on another list item, their HTML code switches positions using the DataTransferobject. This action also makes them switch positions visually and is also convenient to connect it with PHP and save the item order in the database.

Conclusion

This is just a basic implementation of the native HTML5 drag and drop. It can be customized in many ways, such as saving the item position, removing the items from the list, using a fixed number of positions, using two item lists.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

6 Web Resources for Coders

6 Online Coding Resources

One of the most rapidly growing job industries today is coding. As more and more of the world moves to a digital format, the demand for skilled coders continues to increase. With a high demand for the skillset, coders tend to be very well compensated for their work. Furthermore, coders

Malware Removal and Protection Software You Should Use in 2023 

The Best Malware Removal Software in 2023

In the modern world, computers are practically a necessity for every home. Computers give us access to vast amounts of information through the internet, as well as provide us with innovative programs and applications like social media, email, and much more. But with these benefits also come the threats of

Why Technology Literacy is So Important for Modern Workers 

Why Technology Literacy is So Important for Modern Workers 

Importance of Having Technology Literacy Today’s world is completely reliant on technological products and advancements. In the current technology-based era, it is crucial to have technology literacy. And these particular instances might be most suitable for the cases of modern workers dealing with modern equipment, especially in the construction sector. 

The Small Business & Data Analytics: What You Need to Know

The Small Business & Data Analytics: What You Need to Know

The objective of any business is to afford its community a product and create extra money for the services provided. Ideally, this always goes as planned, but at times when it doesn’t, having an extra eye on the data analytics of your small business may make a significant difference. Metrics

Break Into Tech Sales in 4 Easy Steps

Break Into Technology Sales in 4 Easy Steps

One of the fastest-growing industries of the 21st century is undoubtedly tech sales. Between innovations like computers, AI, social media, and more, tech is everywhere. And the demand continues to increase. With constant innovations and massive demand, tech sales have become an extremely lucrative industry. As such, there is no