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

Asked

Viewed 70 times

1

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

#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>

  • Maybe it is better not to link the Mousemove to the block, but to start the movement in the click, independent of the "Hover", following the mouse in the whole page.

  • I think there’s something here that looks like what you want, but it was done with jQuery... https://answall.com/questions/312832/algu%C3%A9m-could-tell me-how-can-do-this-effect-to-pass-the-mouse/312864#312864

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 event mousemove and mouseup you apply to the whole document. So when you click on the block (mousedown) will change the state of the false for true, making the block move with the mouse cursor. By releasing the button (mouseup), the variable is again false, causing the block no longer to move.

Behold:

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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.