Currently, I am developing a game that involves clicking and dragging using jQuery. Within the red game div, when you click an object appears that can be dragged around. To view a demonstration of this functionality, you can visit the following fiddle link:
https://jsfiddle.net/r9pet266/6/
In order to achieve a smooth experience, I added a CSS transition property to the block to create a slight delay between mouse movement and block movement.
The issue arises when selecting outside the game div; subsequent clicks and drags inside the area become jumpy. Can anyone explain why this occurs?
HTML
<div id="outer">
<div id="game"></div>
<div id="instructions">
1. Click and drag inside the red box --> smooth <br>
2. Click on the green <br>
3. Click and drag inside the red box --> jumpy
</div>
</div>
CSS
#outer {
height: 500px;
background: green;
}
#instructions {
position: absolute;
top: 350px;
left: 100px;
}
#game {
position: relative;
display: inline-block;
width: 300px;
height: 270px;
background: red;
}
.block {
transition: 100ms;
position: absolute;
width: 80px;
height: 80px;
background: black;
}
JavaScript:
var $block;
$('#game').mousedown(function (e) {
e.preventDefault();
$block = $('<div>');
$block.addClass('block');
updatePosition(e);
$('#game').append($block);
$('#game').mousemove(updatePosition);
$(window).one('mouseup', function () {
$block.remove();
$('#game').off('mousemove');
});
});
function updatePosition (e) {
$block.css('top', e.pageY - 45 + 'px');
$block.css('left', e.pageX - 45 + 'px');
}