I am currently working on a drag and drop project and have encountered a minor issue. My goal is to disable the draggable item after it has been dropped onto the droppable area. I have created a function called disableDrag
, but I am receiving an error in the console and the function is not executing as expected. Does anyone have any insights into why this might be happening? Additionally, I am open to suggestions for alternative approaches to achieve this functionality.
Here is the HTML setup:
<div class="container">
<div id="key" class="fragment">
<div class="key"></div>
</div>
<div id="dragonkey" class="fragment">
<div class="key"></div>
</div>
<div id="inventory">
<div class="slot" id="slot1"></div>
<div class="slot" id="slot2"></div>
</div>
</div>
CSS styling:
.container{
width:300px;
height:300px;
background-color:#ccc;
}
#key, #dragonkey{
width:20px;
height:20px;
position:absolute !important;
z-index:999;
cursor:pointer;
background-color:DarkGoldenRod;
transform:rotate(45deg);
-webkit-transform:rotate(45deg);
-moz-transform:rotate(45deg);
-o-transform:rotate(45deg);
}
#key{
top:5%;
left:5%;
}
#dragonkey{
top:15%;
left:5%;
}
#inventory{
width:68px;
height:68px;
position:relative;
float:right;
margin:5% 5% 0 0;
transform:rotate(45deg);
-webkit-transform:rotate(45deg);
-moz-transform:rotate(45deg);
-o-transform:rotate(45deg);
}
.slot{
border:2px solid #fff;
width:30px;
height:30px;
float:left;
}
#slot1, #slot2{
background-color:rgba(0,0,0,1);
}
.ui-droppable-active{
background-color:rgba(184,134,11,0.7) !important;
}
Below is the jQuery setup:
// JavaScript document
$(document).ready(function() {
$("#key").draggable({
containment: ".container"
});
$("#dragonkey").draggable({
containment: ".container"
});
$("#slot1").droppable({
accept: "#key",
drop: dropAnimate
});
$("#slot2").droppable({
accept: "#dragonkey",
drop: dropAnimate
});
function dropAnimate(event, ui) {
console.log( $(ui.draggable).attr('id'));
var $this = $(this);
var width = $this.width();
var height = $this.height();
var cntrLeft = (width / 2) - (ui.draggable.width() / 2);
var cntrTop = (height / 2) - (ui.draggable.height() / 2);
ui.draggable.position({
my: "center",
at: "center",
of: $this,
using: function(pos) {
$(this).animate(pos, "slow", "linear");
}
});
disableDrag();
}
function disableDrag () {
$(this).draggable({
disabled: true
});
console.log("DISABLED");
}
}); <!-- END OF DOCUMENT READY -->