How to solve the problem of the square when dragged by the mouse cursor?

1

When the movement of the mouse is rapid it ends up leaving the square and thus the square does not move along with the mouse, I would like to know a solution so that the square always accompanies the mouse independent of him leaving the field of the square with the cursor o by dragging.

#bloco{
	width: 100px;
	height: 100px;
	background-color: orangered;
	position: absolute;
}
<div id="bloco"></div>

<script>

	bloco.style.top = 10+"px"
	bloco.style.left = 10+"px"

	bloco.onmousemove=function(e){
		
		
		x = e.movementX
		y = e.movementY
		
		if( e.buttons > 0 ){
			bloco.style.top = (parseInt(bloco.style.top)+y)+"px"
			bloco.style.left = (parseInt(bloco.style.left)+x)+"px"
		}
	}

	bloco.onmouseout=function(e){
		
		// k = 0;
	}
</script>
    
asked by anonymous 30.12.2018 / 14:06

1 answer

0

Create 2 more events: mousedown and mouseup . Also create a variable that will serve as a condition for the block to move.

The mousemove and mouseup event applies to the entire document. So when you click on the block ( mousedown ) it will change the state of the false variable to true , causing the block to move with the mouse cursor . When you release the button (% with%), the variable returns false , causing the block to no longer move.

See:

var bloco = document.getElementById("bloco");

bloco.style.top = 10+"px"
bloco.style.left = 10+"px"

var drag;

bloco.onmousedown=function(e){
   drag = true;
}

document.onmouseup=function(e){
   drag = false;
}

document.onmousemove=function(e){
   
   x = e.movementX
   y = e.movementY


   if( e.buttons > 0 && drag ){
      bloco.style.top = (parseInt(bloco.style.top)+y)+"px"
      bloco.style.left = (parseInt(bloco.style.left)+x)+"px"
   }
   
}
#bloco{
	width: 100px;
	height: 100px;
	background-color: orangered;
	position: absolute;
}
<div id="bloco"></div>
    
30.12.2018 / 15:30