Skip to Navigation or
Skip to Content

Simple Mobile Web Browser Drag And Drop

Feeds

RSS Feed

<< June | July | August >>

Friday, 9th July 2010

I recently discovered a problem on my mobile device with drag and drop. The problem is that mobile devices are now an inherently drag and drop environment, where almost everything can be done at the swipe of a finger. You would think that this would make it easier to have items on your web page that can be dragged around, but actually it makes it more difficult. The reason it is harder is that when a user performs a swipe or drag action while browsing a website, the mobile device captures this event and uses it to scroll around the page. This means that your draggable item never receives the instruction to move.

I have been researching the best way to get around this issue and my current work can be seen in a very basic demo, titled the "Mobile Device Drag Drop Test".

Essentially, the best fix I have found so far that works on a mobile device is to harness the mouse-down event on the element to drag and the mouse-up event on the target element. The reason for using mouse-down and mouse-up is because this then behaves like a drag in browsers on non-mobile devices. To get it work on a mobile device, you tap the item and then tap the target - try out the demo in a normal browser and mobile browser to see the results, the full jQuery JavaScript is below, including the bits that pump out what is happening onto the page.

		var currentDrag;
		var currentDrop;
	
		function SetCurrentDrag(id) {
			$(".drag").removeClass("selected");
			$(id).addClass("selected");
			currentDrag = id;
			$("#dragging").html(id);
		}
	
		$(document).ready( function () {
			$(".drag").live("mousedown", function() {
				var id = "#" + $(this).attr("id");
				SetCurrentDrag(id);
				return false;
			});
			
			$(".drop").live("mouseup", function () {
				var id = "#" + $(this).attr("id");
				if (currentDrag.length > 1) {
					$(currentDrag).remove().prependTo(id);
					SetCurrentDrag("");
					$("#dropping").html(id);
				}
				return false;
			});
		});

 

You Are Here: Home » Blog » Simple Mobile Web Browser Drag And Drop

 

I use a cookie on this website. This cookie doesn't contain or relate to any personal information and it isn't shared with any other website, it just ensures that I don't count you more than once in my website statistics. The Privacy and Electronic Communications Regulations require me to ask your permission to use this cookie, so please indicate below that you are happy for me to do this - I will remember your selection with a cookie, so if you accept I won't ask again...