Reputation: 4049
Using the code below, how can I get the id of an element being dragged? And then, if the element ID does not equal 1 then revert element to original position?
Thanks,
<script> //DRAG AND DROP EVENTS
$(".container").delegate(".draggable","mouseenter",function() {
$(".draggable").draggable({
revert : function(event, ui) {
$(this).data("uiDraggable").originalPosition = {
top : 0,
left : 0
};
return !event;
},
start: function(event,ui) { // GET ID OF ELEMENT HERE IS NOT WORKING
var id = ui.draggable.attr("id");
console.log(id);
//GETTING ERROR Uncaught TypeError: Cannot read property 'attr' of undefined
//IF id <> 1 then revert to original position
}
});
});
</script>
Upvotes: 1
Views: 1372
Reputation: 93
Try this:
start: function(event, ui) {
var id = event.target.id;
console.log(id);
}
Upvotes: 1
Reputation: 43156
Inside the function which you pass to the revert option, this
will refer to the jQuery object corresponding to the element being dragged - You can access it's id using this.attr("id")
.
Side notes:
event
or ui
parameters, the only argument it seems to receive is a booleanui
parameter inside start
callback doesn't have a draggable property$(".draggable").draggable({
revert: function (event, ui) {
return (this.attr("id")==1);
}
});
div {
width:50px;
height:50px;
line-height:50px;
margin:5px;
text-align:center;
background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
<div id="1" class="draggable">1</div>
<div id="2" class="draggable">2</div>
Upvotes: 1