Today, I was helping a friend who is learning web development. He was trying to create a way to move a div element using click and drag. Here is how we implemented it…
<head>
<title>jQuery Move-able Div</title>
<link href='./includes/styles.css' rel='stylesheet' type='text/css' />
<script src='./includes/jQuery1.6.4.js' type='text/javascript'></script>
<script type='text/javascript'>
var x1,y1,x2,y2,distX,distY;
$(document).ready(function(){
$('#moveableDiv').mouseover(function(){
$(this).css("cursor","pointer");
});
$('#moveableDiv').bind('mousedown', function(event){
x1 = event.clientX;
y1 = event.clientY;
var x3 = parseInt($('#moveableDiv').css('left'));
var y3 = parseInt($('#moveableDiv').css('top'));
$(this).bind('mousemove', function(event1) {
x2 = event1.clientX;
y2 = event1.clientY;
distX = x2 - x1;
distY = y2 - y1;
var newX = x3 + distX;
var newY = y3 + distY;
$(this).css('left', newX);
$(this).css('top', newY);
});
});
$(document).mouseup(function() {
$(this).unbind('mousemove');
});
});
</script>
</head>
<body>
<div id='moveableDiv'>Hello</div>
</body>
</html>
Let’s break this down and see what is happening!
Create the style sheet to better distinguish the move-able div element contained in the file, “includes/styles.css”:
div#moveableDiv{
width: 200px;
height: 100px;
position: absolute;
left: 50px;
top: 50px;
z-index: 1;
border: 1px black solid;
background-color: #ff9999;
}
then, comes the javascript!
Declare variables used to keep track of the div location:
var x1,y1,x2,y2,distX,distY;
Then when the DOM is ready…
$(document).ready(function(){
attach a mouseover event that changes the cursor into a hand pointer…
$('#moveableDiv').mouseover(function(){
$(this).css("cursor","pointer");
});
Bind the mousedown event, assigning the mouse coordinates in x1 and y1…
$('#moveableDiv').bind('mousedown', function(event){
x1 = event.clientX;
y1 = event.clientY;
then assign the original div location in x3 and y3…
var x3 = parseInt($('#moveableDiv').css('left'));
var y3 = parseInt($('#moveableDiv').css('top'));
Bind the mousemove event to actually do the move.
$(this).bind('mousemove', function(event1) {
x2 = event1.clientX;
y2 = event1.clientY;
This is accomplished by tracking the location of the mouse as it moves in x2 and y2 and calculating the difference between the original location and the current…
distX = x2 - x1;
distY = y2 - y1;
var newX = x3 + distX;
var newY = y3 + distY;
then assigning it to the css left and top properties for the div element…
$(this).css('left', newX);
$(this).css('top', newY);
});
});
Finally, unbind the mousemove event on mouseup to release the mouse…
$(document).mouseup(function() {
$(this).unbind('mousemove');
});
});
</script>
Let me know your thoughts on this tutorial below in the comments, I look forward to hearing from you! You can check out my website at http://www.manzwebdesigns.com/ if you so desire.
Thanks!
Bud Manz
