user3758078
user3758078

Reputation:

Cancel drag before it starts

I'm using jQuery UI sortable and am simply trying to prevent dragging if condition is true. I've come across this solution: https://stackoverflow.com/a/18470982/3758078 but that cancels the drag when drag stops, not before it begins. Other solutions advise to use return false; in the sort: event but that simply returns an error.

    $(elements).sortable({
        start: function() {
           if( true ) {
               //cancel dragging before it begins
           }
        }
    });

Upvotes: 2

Views: 950

Answers (2)

alessandrio
alessandrio

Reputation: 4370

Try it....

https://stackoverflow.com/a/1324065

Could create a DisableDrag(myObject) and a EnableDrag(myObject) function

myObject.draggable( 'disable' )

Then

myObject.draggable( 'enable' )

Upvotes: 1

Dekel
Dekel

Reputation: 62536

Here is a working example using the start callback.
You can use the allowdrag checkbox to enable/disable the dragging functionality:

$(document).ready(function () {
    $("#draggable").draggable({
      revert: "invalid",
      start: function(e) {
        if (!$('#allowdrag').is(':checked')) {
          e.preventDefault();
        }
      }
    });
    $("#Dropable").droppable({
        activeClass: "ui-state-highlight",
        drop: function (event, ui) {
            alert("dropped!");
        },
        tolerance: 'fit'
    });
});
#draggable {
    width: 150px;
    height: 150px;
    padding: 0.5em;
}
#Dropable {
    height:300px;
    width:400px;
    border: 2px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.js"></script>
<input type="checkbox" id="allowdrag" /><label for="allowdrag"> Allow drag</label><br />
<div id="draggable" class="ui-widget-content">
    <p>Drag me around</p>
</div>
<div id="Dropable">Droppable area</div>

You can change the if (!$('#allowdrag').is(':checked')) { part to whatever you want to check in order to enable/disable the drag option.

Upvotes: 5

Related Questions