Drag and Drop- Change HTML Elements Position in the Page

Written by @m_k_amin 19 May 2013

Another great feature of HTML5 is Drag and Drop. It allows you to drag everything and drop on everything else; Then its you to decide what must happen next. This code is an example of changing HTML elements position in the page. Click on the one of the elements below (Div and Table), drag it, move it to the specified location, and drop it! This code uses the "Text" data transfer for sending the object ID to the target place. It's simple and beautiful; Enjoy!

Code Snippet:

                                                
                                                <!-- this script is provided by https://www.html5freecode.com coded by: Kerixa Inc. -->
<!-- This Script is from www.html5freecode.com, Coded by: Kerixa Inc-->

<head>
<script>
function saveobj(ev){
ev.dataTransfer.setData("Text", ev.target.id)
}
function allowdrag(ev){
ev.preventDefault()
}
function addobj(ev){
allowdrag(ev)
var objid= ev.dataTransfer.getData("Text")
ev.target.appendChild(document.getElementById(objid))
}
</script>
<table style="width: 400px">
	<tr>
		<td style="width: 160px">
		
			<div style="border: thick solid maroon; width: 120px; height: 24px; text-align: center; color: #1F23CA;"
			ID="txt" draggable="true" ondragstart="saveobj(event)"
			>Drag HTML Div</div>
		</td>
		<td rowspan="2">
		
			<div ondragover="allowdrag(event)" ondrop="addobj(event)" style="border: 1px solid navy; height: 133px; padding: 1px 4px; width: 169px; text-align: center; color: #9D9DA7">
			Drop Here</div>
		
		</td>
	</tr>
	<tr>
		<td style="width: 160px">
			
			<table style="border-style: solid; width: 80; border-width: 1px; height: 78;" draggable="true" ondragstart="saveobj(event)" id="tbl" >
				<tr>
					<td style="border-style: solid; border-width: 1px; color: #1F23CA;">
					HTML</td>
					<td style="border-style: solid; border-width: 1px; color: #1F23CA;">
					Table</td>
				</tr>
				<tr>
					<td style="border-style: solid; border-width: 1px; color: #1F23CA;">
					Drag</td>
					<td style="border-style: solid; border-width: 1px; color: #1F23CA;">
					It</td>
				</tr>
			</table>
			
		</td>
	</tr>
</table>
</head>

<div style="text-align: center"><br><font face="Tahoma"><a target="_blank" href="http://www.html5freecode.com"><span style="font-size: 8pt; text-decoration: none">HTML5 Free Code</span></a></font></div><a target='_blank' href='https://www.html5freecode.com' style='font-size: 8pt; text-decoration: none'>Html5 Free Codes</a>                                                
                                            

Example:


About @m_k_amin

This user is pending a biography.

M

Comments


Here you can leave us commments. Let us know what you think about this code tutorial!

0 / 300

TRENDING POST
1
2
3
4
5
VISITORS
Online Users: 12
Recent Members: Afzal, FOTPU
advertisement 2