Movement control in jQuery

how can i control the movement of draggable in jquery?

I need to do something similar to "snap to grid" where draggable moves each pixel "x" and "y"

I can’t use "grid: [x, y]" (2D) because I need to do a drag on an isometric grid (3D) (I will develop a grid later, first I will need to control the drag)

for example: when I start dragging, draggable should not move, it should snap to a different position when "x" and "y" are in certain conditions

early!

+4
source share
2 answers

ok, I found what I was looking for!

in this link was part of the code i need

The code is as follows:

// inside drag: function (event, ui)

var offset = $(this).parent().offset(); var GRID_SPACING = 10; var SELECTION_OFFSET_X = 10; var SELECTION_OFFSET_Y = 3; if (parseInt(event.clientX / GRID_SPACING) % 2 == 0) { var row = Math.floor((event.clientY - offset.top) / GRID_SPACING) + Math.floor(event.clientX / (2 * GRID_SPACING)); var col = -Math.floor((event.clientY - offset.top) / GRID_SPACING) + Math.floor((event.clientX + GRID_SPACING) / (2 * GRID_SPACING)); } else { var row = Math.floor((event.clientY + GRID_SPACING / 2 - offset.top) / GRID_SPACING) + Math.floor(event.clientX / (2 * GRID_SPACING)); var col = -Math.floor((event.clientY + GRID_SPACING / 2 - offset.top) / GRID_SPACING) + Math.floor((event.clientX + GRID_SPACING) / (2 * GRID_SPACING)); } var new_x = row * GRID_SPACING + col * GRID_SPACING - SELECTION_OFFSET_X; var new_y = (row * (GRID_SPACING / 2)) - (col * (GRID_SPACING / 2)); if(event.clientX == new_x + GRID_SPACING * 2) { ui.position.left = new_x; new_x = event.clientX; } if(event.clientY == new_y + GRID_SPACING) { ui.position.top = new_y; new_y = event.clientY; } ui.position.left = new_x; ui.position.top = new_y; 

I changed some constants to adapt to my grid ...

0
source

Try using the parameters inherent in the .draggable () function at http://jqueryui.com/demos/draggable/

basically it says that the snap parameter is set to true :

 $( ".selector" ).draggable({ snap: true, snapMode:'outer', snapTolerance:40 }); 

snapMode "... determines to which edge of the anchor elements the dragged object is bound. It is ignored if the anchor is false. Possible values ​​are" internal "," external "," both ". And snapTolerance -" ... The distance in pixels from the edges of the element bindings at which the binding occurs. "

Or try using the grid parameter. This is designed to do exactly what you want: "... the Grid anchors the drag and drop helper element to the grid, every x and y pixels. Array values: [x, y] Code examples":

Initialize the draggable with the specified grid option.

 $( ".selector" ).draggable({ grid: [50, 20] }); 

Get or set the grid parameter after init.

 //getter var grid = $( ".selector" ).draggable( "option", "grid" ); //setter $( ".selector" ).draggable( "option", "grid", [50, 20] ); 

Hope this helps you.

+1
source

Source: https://habr.com/ru/post/1347559/


All Articles