jQuery UI draggable Options snap

Set snap to true will make draggable elements snap to all other draggable elements.
$("#eleID").draggable({ snap: true  });
or using selector
$("#eleID").draggable({ snap: "#drag1"});

Here are two examples, one set snap to true, the other using selector, try to drag pink square close
to gray square, once square is close enough to another, it will snap to gray square.

Related option
snap modesnap tolerance
ExampleJquery ui draggable options snap
Source Code Expand
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script type="text/javascript" src="http://www.pureexample.com/js/lib/jquery.ui.touch-punch.min.js"></script>

<!-- CSS -->
<style type="text/css">
.drag {
    width: 100px;
    height: 100px;
    line-height: 100px;
    border: 1px solid black;
    cursor: pointer;
    border-radius: 10px;
    text-align: center;
    background-color: lightpink;

.container {
    background-color: lightblue;
    width: 300px;
    height: 400px;
    border: 1px solid black;
    float: left;
    margin-right: 30px;

<!-- Javascript -->
$(function () {        
		containment: "#c1",
		stack: ".drag",
		snap: true        

		containment: "#c1",
		stack: ".drag",
		snap: false        

		containment: "#c2",
		stack: ".drag",
		snap: "#drag4"        

		containment: "#c2",
		stack: ".drag",
		snap: "#drag6"        

<!-- HTML -->
<div id="c1" class="container">
    <div style="text-align:center">snap set to true</div>
    <div id="drag1" class="drag">snap:true</div>
    <div id="drag2" class="drag" style="background-color:lightgray">snap:false</div>
<div id="c2" class="container">
    <div style="text-align:center">snap using selector</div>
	<div id="drag3" class="drag" style="position:relative;left:20px;float:left">snap to 1</div>
    <div id="drag4" class="drag" style="position:relative;left:30px;float:left;background-color:lightgray;border:1px dotted black;z-index:1">1</div>
    <div id="drag5" class="drag" style="position:relative;left:20px;top:150px;float:left">snap to 2</div>
    <div id="drag6" class="drag" style="position:relative;left:30px;top:150px;float:left;background-color:lightgray;border:1px dotted black">2</div>

comments powered by Disqus