jsfiddle link .
I want the mousedown event to fire on #flyingDiv , I can move it around #holder , when mouseup and mouse leave #holer , I can't move it. In my code, sometimes #flyingDiv is located next to the black frame when I move the mouse in the center of #holder .
HTML:
<div id="holder" style="position: relative; margin: 20px auto; border: 1px solid black; width: 400px !important; height: 400px !important;"> <div id="flyingDiv" style="position: absolute; background-color: green; width: 10px !important; height: 10px !important; left: 195px; top: 195px;"></div> </div>
Javascript:
$(function(){ var fd = $("#flyingDiv"); $("#flyingDiv").bind("mousedown", function(event) { $(this).attr("pressed", true); }); $("#holder").bind("mouseup", function(event) { $("#flyingDiv").removeAttr("pressed"); }); $("#holder").bind("mousemove", function(event) { var div = $("#flyingDiv"); if (div.attr("pressed")) { var width = div.width(); if (event.offsetX >= width / 2 && ($(this).width() - event.offsetX) >= width / 2) { div.css("left", parseInt(event.offsetX - width / 2) + "px"); } var height = div.height(); if (event.offsetY >= height / 2 && ($(this).height() - event.offsetY) >= width / 2) { div.css("top", parseInt(event.offsetY - height / 2) + "px"); } } }); });
UPD
I found that if event.eventPhase == 3 is an old event. Link
But still, the code does not work fast.
source share