Note that there are some explanatory texts on larger screens.

plurals
  1. POReposition element prior to dragging with jQuery UI
    primarykey
    data
    text
    <p>This is an attempt to solve the problem of drag elements aligning to a grid (I outlined this in a previous question- <a href="https://stackoverflow.com/q/20695744/165673">Getting jQuery draggable to snap to specific grid</a>) </p> <p>So far I've established that the issue is that jQuery calculates the position of the element at the moment that <code>.draggable()</code> is called, and creates the grid relative to the element, instead of relative to the element's parent (which would be more intuitive).</p> <p>In the following solution, we see 3 boxes:</p> <ul> <li><strong>Box 1</strong> starts out at 0,0, and so will be aligned with the parent element's grid.</li> <li><strong>Box 2</strong> starts out at a point not aligned with the grid, and so will never be aligned with it while dragging.</li> <li><strong>Box 3</strong> also starts out at a point not aligned with the grid, but in this case we capture the mouse down event, and reposition the element to the nearest grid point, and only then to we call <code>draggable()</code>.</li> </ul> <p>Option 3 works in so far as the element will now snap in alignment with the grid. The problem is, it takes two mouse events: one to reposition the element, and only on the next mousedown event (after it's turned yellow) will a drag actually kick in.</p> <p>How can I redo this so that the element can be repositioned and then have <code>.draggable()</code> called on it, all with a single mousedown event?</p> <p><img src="https://i.stack.imgur.com/MDl8m.png" alt="Aligning drag elements to grid"></p> <p><strong><a href="http://jsfiddle.net/8RnBf/34/" rel="nofollow noreferrer">http://jsfiddle.net/8RnBf/34/</a></strong></p> <p><strong>JS:</strong></p> <pre><code>$('#box-1').draggable({ grid: [ 20,20 ] }); $('#box-2').draggable({ grid: [ 20,20 ] }); var isDraggable = false; $('#box-3').mousedown(function(e){ console.log('MOUSE DOWN'); if (isDraggable == false) { var $this = $(this); // Reposition to nearest grid position: currentX = parseInt($this.css('left')); currentY = parseInt($this.css('top')); nearestGridX = Math.round(currentX/20) * 20; nearestGridY = Math.round(currentY/20) * 20; $this.css({left:nearestGridX+'px',top:nearestGridY+'px'}); // Turn yellow: $this.css({background:'yellow'}); // Make draggable: isDraggable = true; $this.draggable({ grid: [ 20,20 ], start: function( event, ui ) { console.log('START'); } }); $this.trigger("mousedown"); } }); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload