Robin Andrews
Robin Andrews

Reputation: 3794

JQuery Draggable/Snap Limit Area

How can I limit the area that the "A" can be dragged to to the gameArea div in the code below please?

I need to add more text to be able to submit this question. Is this enough?

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Permutations</title>
<style>
    body{
      font-family: sans-serif;
      font-size: 50px;
      color: green;
    }
    #gameArea{
      margin:20px auto;
      width: 600px;
      height: 400px;
      border: 4px solid green;
      background-color: cyan;
    }
</style>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<script>
    $( function() {
      $( "#draggable" ).draggable({ grid: [ 50, 50 ] });
    } );
</script>
</head>
<body>
    <div id="gameArea">
        <p id="draggable">A</p>
    </div>
</body>
</html>

Upvotes: 0

Views: 828

Answers (2)

mhodges
mhodges

Reputation: 11116

You can use .droppable() for the #gameArea to determine the validity of the drop position, like so:

$(function() {
  $( "#draggable" ).draggable({ 
    grid: [ 50, 50 ],
    revert: "invalid"
  });
  $("#gameArea").droppable({
    accepts: "#draggable"
  });
});

Upvotes: 0

Diptox
Diptox

Reputation: 1809

Hey check the Demo

$( function() {
     $( "#draggable" ).draggable({ containment: "parent" , grid: [ 50, 50 ] });
} );

and resize the width of the #draggable div ,

#draggable
{
    width:50px;
    height:50px;
}

Upvotes: 1

Related Questions