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 Tips for Setting Up a Decentralized Exchange

6 Tips for Setting Up a Decentralized Exchange

There’s no doubt that cryptocurrency is a complex and divisive topic in the modern financial landscape. There are those who are convinced that it’s nothing more than a bubble, but both who are well-informed are able to see the ways in which cryptocurrency can help them both build their fortune

user experience with someone on their phone

5 Ways to Improve Your Customers’ User Experience

They say you can’t judge a book by its cover, but just because they say that doesn’t mean it’s true. Consider how often you choose one sort of product over another just because it appeals to you. Then think about how often you’ve stopped using something because, simply put, it

How to Manage Your Finances after Buying a Home

How to Manage Your Finances after Buying a Home

Buying a home is a milestone in the journey of life – it’s one way to invest your money and create lasting memories. Now you know everything about a home purchase, home mortgage, and what is a conventional 97 loan but do you know what’s next after you sign the

Windows Logging is one of the vital aspects of any Windows system administration. However, it is mostly overlooked until the system develops a problem. This is because logs contain important information needed to troubleshoot and resolve system issues.

The Fundamentals of Windows Logging

Windows Logging is one of the vital aspects of any Windows system administration. However, it is mostly overlooked until the system develops a problem. This is because logs contain important information needed to troubleshoot and resolve system issues. Without it, tech experts might find it difficult to track a computer’s

Interstitial Ads: Best Practices for Successful Campaigns

Interstitial Ads: Best Practices for Successful Campaigns

Interstitial Ads: Best Practices for Successful Campaigns Interstitial ads are full-screen advertisements that appear to grasp the attention of on-site prospects, creating opportunities for brands seeking effective ways to communicate their proposition of value. With such an attention-grabbing format and high-impact visuals, it’s no wonder why interstitial advertising is proving