JavaScript & jQuery; how to make a drag snap

I’m looking for tips from all of you wonderful people who are best suited for drag and drop.

As part of the simple board game I'm currently coding in JS (using jQuery for effects), users should be able to drag tiles from the dock to the grid.

How to perform the following tasks (preferably using jQuery).

  • Enable drag and drop to grid
  • Ensure that items are snapped to each grid square while dragging.
  • If the tile is completely placed in the grid, return to the original place (dock)
  • If the tile is above the grid (fixed at this point), return the current x and y to the function
  • Make some tiles slightly transparent and switch to full color once in place or return to the dock

Sorry to ask such a big question, I just cannot find the exact advice on the Internet that I could achieve this!

Many thanks,

Edit: ANSWERS
1 & 2 resolved by "draggable": http://jqueryui.com/demos/draggable
3 solved by "droppable" http://jqueryui.com/demos/droppable
4 is solved by the above for verification, and then $(this).position.left && $(this).position.top
5 is solved by a simple $(this).css({opacity:0.5}) internal trigger when dragging, and the opposite with finite resistance

Simples!

+7
javascript jquery drag-and-drop
source share
2 answers

There are demos about Interactions :

Draggable

Droppable

Resizable

Selectable

Sortable

I hope these demos can help you.

+4
source share

Hope this helps you, this is for drag and drop binding in jQuery

 var snap = 10; /* the value of the snap in pixels */ var l,t,xInit,yInit,x,y; $(document).mousemove(function(e) { x = e.pageX; y = e.pageY; drag(snap); }); $('#obj').mousedown(function(e){ l=$('#obj').position().left; t=$('#obj').position().top; xInit = e.pageX; yInit = e.pageY; }) function drag(snap){ w=$('#obj').width(); h=$('#obj').height(); var left = l+x-xInit; var top = t+y-yInit; if(!snap==0){ left = (left/snap).toFixed()*snap; top = (top/snap).toFixed()*snap; $('#obj').css('left',left); $('#obj').css('top',top); }else{ $('#obj').css('left',left); $('#obj').css('top',top); } } 
+1
source share

All Articles