The following example will present a page with two draggable squares I made. Nomatter how hard I tried though, I can’t figure out why both squares are being dragged at the same time when I try to drag just one.
<html>
<head>
<title>Hello!</title>
<script type="text/javascript" src="/js/jquery-1.7.1.min.js"></script>
</head>
<body>
<h2>Hello</h2>
<div style="border: 1px solid red; height: 300px; position: relative;" id="canvas">
<div style="background-color: yellow; width: 100px; height: 100px; position: relative;" class="square" />
<div style="background-color: blue; width: 100px; height: 100px; position: relative; top: 200px; left: 200px;" class="square" />
</div>
<script type="text/javascript">
var mousePointsOn;
var holdX;
var holdY;
var track = function(e) {
mousePointsOn.css('left', e.pageX - $("#canvas").offset().left - holdX);
mousePointsOn.css('top', e.pageY - $("#canvas").offset().top - holdY);
};
$('#canvas').delegate('.square', 'mousedown', function(e) {
holdX = e.pageX - $(this).offset().left;
holdY = e.pageY - $(this).offset().top;
e.preventDefault();
mousePointsOn = $(this);
$('body').bind('mousemove', track);
});
$('#canvas').delegate('.square', 'mouseup', function() {
$('body').unbind('mousemove', track);
});
</script>
</body>
</html>
Thank you.
You cannot use
<div />to create a div with no content. The browser has actually interpreted the first square as an unclosed div, and nested the second div, as well as the script below inside it. Use<div></div>instead.