Ultra small code to drag everything in HTML pages

A frequent question I receive from my readers is about how to implement a simple script to drag elements in a web page. So in this post I want to illustrate the simplest method I know and use to drag everything in HTML pages, using just three rows of Javascript code.

In this post I provided a very basic script quick to reuse and customize in your web projects (in the live preview I added some little additional features respect the content of this tutorial). This is the result:


Download this tutorial Live preview



HTML code: HTML code is very simple. You have to add a main layer with an ID (I used "draggables") and some DIV layers inside that layer. In this way all layers contained inside the layer "draggables" will be draggable when you select them. This is the structure:



Copy and paste this code in your page:

<div id="draggables">
<div>
Some content Here...</div>
<div>Some content Here...</div>
<div>Some content Here...</div>
</div>


JavaScript code: Now take a look at this simple code which enable drag features. Before all add a link to MooTools farmework in the <head> tag of the page:

<script type="text/javascript" src="mootools.svn.js">
</script>

Now, copy and paste this simple unobtrusive code:

<script type="text/javascript">
window.addEvent('domready', function(){
$('#draggables div').each(function(drag){
new Drag.Move(drag);});
});
</script>

Simple no? Just in three rows! In this way when you click on a div element contained inside the layer #draggables it will be draggable. In this tutorial I used DIV layers for my draggable elements but you can use every tag you want (p, h1, h2, ul, li....). The only thing you have to change is HTML code and DIV - with the tag you use (p, h1, h2, ul, li....) - in this line:

$('#draggables div').each(function(drag)


You can also add a custom style to your draggable elements using a simple CSS class I called "drag". For example, change the previous code HTML with the following:

<div id="draggables">
<div class="drag"
>Some content Here...</div>
<div class="drag">Some content Here...</div>
<div class="drag">Some content Here...</div>
</div>

...and CSS code could be something like this:

.drag{
border:solid 6px #DEDEDE;
background:#FFF;
width:200px;
height:150px;
...
}

That's all! Try it and download the source code ready to use in your porject.

Download this tutorial Live preview
Tags: , , , ,

About author

Information Technology Blog provides you with information and links to computer tips, tricks, solutions, computer components, smartphone, tablet, news and relevant information to IT related topics.

0 comments

Leave a Reply