jquery

HTML 5 - Drag and Drop

| 0 comments | html5 jquery

I am not sure who invented drag-and-drop but it has been with us I guess since the creation of the mouse. It was something that has never really made it to the world wide web, even though it is done day to day on the desktop.

HTML 5 now adds the draggable attribute allowing a simple method of getting the browser to do something when content is moved around the page. For an example, a list of things that you could move and order in preference.

I have add a little application to the front page of dylanjones.info where you can drag items from my interest bubble into a box which then displays some extra information relating to that item. This particluar example is not the best method to display added content as a click would be just as efficient but I wanted to give it a go.

The HTML for the draggable items is simply:

<span id='drag-2' descr='HTML5: I am learning about HTML5 as it comes out - it is great fun and provides lots of opportunities' draggable='true' ondrag='pickup(this)'>HTML5</span> <span id='drag-5' descr='Baking: I am very found of Bakery goods, mainly cake, cookies and sweet things' draggable='true' ondrag='pickup(this)'>Baking</span> <span id='drag-6' descr='Welsh: I lived in Wales for a long time' draggable='true' ondrag='pickup(this)'>Welsh</span> <span id='drag-8' descr='Student: I am a student' draggable='true' ondrag='pickup(this)'>Student</span>

The "dropbox" is defined as:

<div id="dropbox" ondrop="drop(this)" ondragenter="return false" ondragover="return false"> <p>drag and drop stuff from the cloud above here</p> </div>

Then javascript and jQuery does the rest:

<script type='text/javascript'> var text = 'Error: Oh Balls'; function pickup(target) { text = $(target).attr('descr'); } function drop() { $('#dropbox').html('<p>' + text + '</p>'); } </script>

Very simple indeed!

To summarise: you add draggable=true to elements you wish to drag, on drag you trigger an event, make a dropbox or use an image or something that then triggers an event ondrop - easy peasy.