I have been trying to learn jQuery to expand my abilities, so I tried emulating the jQuery UI ".draggable()" behavior.
The spinet shows the problem directly, I don't understand why the .mousedown event is triggering when I click on #Box, how can I get it to only trigger when clicking on #MyBox?
P.S. This is purely for the purpose of understanding jQuery, I have no intention to use this code anywhere.
var down, x, y
$(document).ready(function(){
$("#Box").draggable()
$("#MyBox").mousedown(function(event){
down = true
var pos = $(this).offset();
x = event.pageX - pos.left;
y = event.pageY - pos.top;
});
$(document).mouseup(function(event){
down = false
})
$(document).mousemove(function(event){
$("span").text("X: " + event.pageX + " Y: " + event.pageY);
if(down)
{
$("#MyBox").offset({left:event.pageX-x, top:event.pageY-y})
}
})
});
* {
background-color: white;
}
#MyBox {
position: absolute;
background-color: blue;
width: 100px;
height: 100px;
}
#Box {
left: 250px;
position: absolute;
background-color: red;
width: 100px;
height: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script
src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"
integrity="sha256-eGE6blurk5sHj+rmkfsGYeKyZx3M4bG+ZlFyA7Kns7E="
crossorigin="anonymous"></script>
<div class='test'>
<span>Drag a box</span>
<div id='MyBox'/>
<div id='Box'/>
</div>