Sapnesh Naik
Sapnesh Naik

Reputation: 11636

How to get element in jQueryUI draggable revert function?

I know that jQuery draggable can accept a function for revert action.

$(".clipboard-li").draggable({
     revert: function (event) {
         console.log(event) // boolean value
     }
});

But the parameter being passed to this function is a boolean.
How can I get the the element currently being dragged in this function?

Upvotes: 2

Views: 726

Answers (2)

Krzysztof Janiszewski
Krzysztof Janiszewski

Reputation: 3834

revert is an option where you can set

Whether the element should revert to its start position when dragging stops

If you want to get the element after you drag it somewhere use stop event

$(".clipboard-li").draggable({
  revert: function(event) {
    return $(this).hasClass("revert"); //You can set it either to true or false
  },
  stop: function( event, ui ) {
    console.log($(event.target).attr("class"));
  }
});
.clipboard-li {
  cursor: move;
  width: 150px;
  height: 150px;
  border: 1px solid #000;
  display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.10.4/jquery-ui.min.js"></script>

<div class="container">
  <div class="clipboard-li">
  </div>
  <div class="clipboard-li revert">
  </div>
  <div class="clipboard-li">
  </div>
</div>

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

The revert handler function runs under the scope of the element being dragged; it's not passed in as an argument. As such you can use the this keyword to reference the element:

$('.drag').draggable({
  revert: function() {
    return this.prop('id') != 'allow';
  }
})
.drag {
  width: 75px;
  height: 75px;
  background-color: #CCC;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<div class="drag" id="allow">Allowed</div>
<div class="drag" id="deny">Denied</div>

Upvotes: 1

Related Questions