JQuery Tutorials

Drag a layer, with a handle

Make a link to these two JQuery files

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>

Create CSS styles

Create a style for the content layer and the handle. For this example I used a <span> with a background image

<style type="text/css">
#myLayer {
width: 400px;
height: 200px;
border: 1px solid #ccc;
background: #f0f0f0;
font: 10px Verdana, Geneva, sans-serif;
}
.myLayerTitle {
background: #ccc;
padding: 8px 10px;
}
.myLayerContent {
padding: 10px;
}
#myDragIcon {
float: right;
width: 15px;
height: 15px;
background:url(drag.png) no-repeat;
}
</style>

Create a function to drag the layer and a function for the handle

<script>
$(document).ready(function(){
$("#myLayer").draggable();
$("#myLayer").draggable({cursor:'move'});
$("#myLayer").draggable({handle:'#myDragIcon'});
});
</script>

Add a layer on the page

<div id="myLayer">
<div class="myLayerTitle"><span id="myDragIcon"></span>Drag</div>
<div class="myLayerContent">Click on the icon to drag this layer</div>
</div>

Demonstration

Drag
Click on the icon to drag this layer

Background Image

drag_large.png

drag.png; original size: 15x15px;

 

The Whole Code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Drag a Layer</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<style type="text/css">
#myLayer {
width: 400px;
height: 200px;
border: 1px solid #ccc;
background: #f0f0f0;
font: 10px Verdana, Geneva, sans-serif;
}
.myLayerTitle {
background: #ccc;
padding: 8px 10px;
}
.myLayerContent {
padding: 10px;
}
#myDragIcon {
float: right;
width: 15px;
height: 15px;
background:url(drag.png) no-repeat;
}
</style>
<script>
$(document).ready(function(){
$("#myLayer").draggable();
$("#myLayer").draggable({cursor:'move'});
$("#myLayer").draggable({handle:'#myDragIcon'});
});
</script>
</head>
<body>
<div id="myLayer">
<div class="myLayerTitle"><span id="myDragIcon"></span>Drag</div>
<div class="myLayerContent">Click on the icon to drag this layer</div>
</div>
</body>
</html>

JQuery Tutorials
Other Tutorials