jQuery UI & Draggable: Snap To Element Or Grid

jQuery UI Draggable – Snap to element or grid

jQuery UI allows snapping the draggable to the inner or outer boundaries of a DOM element. Use the snapsnapMod (inner, outer, both), and snapTolerance (distance in pixels the draggable must be from the element when snapping is invoked) options.

Or snap the draggable to a grid. Set the dimensions of grid cells (height and width in pixels) with the grid option.

<!doctype html>
<html lang='en'>
<head>
    <meta charset='utf-8'>
    <title>jQuery UI Draggable - Snap to element or grid</title>
    <link rel='stylesheet' href='//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css'>
    <script src='//code.jquery.com/jquery-1.9.1.js'></script>
    <script src='//code.jquery.com/ui/1.10.4/jquery-ui.js'></script>
    <style>
        .draggable { width: 90px; height: 80px; padding: 5px; float: left; margin: 0 10px 10px 0; font-size: .9em; }
        .ui-widget-header p, .ui-widget-content p { margin: 0; }
        #snaptarget { height: 140px; }
    </style>
    <script>
        $(function() {
            $( '#draggable' ).draggable({ snap: true });
            $( '#draggable2' ).draggable({ snap: '.ui-widget-header' });
            $( '#draggable3' ).draggable({ snap: '.ui-widget-header', snapMode: 'outer' });
            $( '#draggable4' ).draggable({ grid: [ 20, 20 ] });
            $( '#draggable5' ).draggable({ grid: [ 80, 80 ] });
        });
    </script>
</head>
<body>

<div id='snaptarget' class='ui-widget-header'>
    <p>I'm a snap target</p>
</div>

<br style='clear:both'>

<div id='draggable' class='draggable ui-widget-content'>
    <p>Default (snap: true), snaps to all other draggable elements</p>
</div>

<div id='draggable2' class='draggable ui-widget-content'>
    <p>I only snap to the big box</p>
</div>

<div id='draggable3' class='draggable ui-widget-content'>
    <p>I only snap to the outer edges of the big box</p>
</div>

<div id='draggable4' class='draggable ui-widget-content'>
    <p>I snap to a 20 x 20 grid</p>
</div>

<div id='draggable5' class='draggable ui-widget-content'>
    <p>I snap to a 80 x 80 grid</p>
</div>


</body>
</html>
Try The Code

If you move the box around, you will find that the snap to 20×20 grid provides a smaller movement where snap to 80×80 provides a bigger movement of the box.

Series Navigation<< jQuery UI & Draggable: Events
jQuery UI & Draggable: Handles >>