Reputation: 63
I am trying to make a item system for my game, which will allow players to move items between slots by dragging and dropping them. As my test, I made a basic system with an item that can be dragged and then should, if dropped over the slot (black square), appear inside of it. However, it appears my ondrop event isn't firing.
I tried commenting out my normal code and put in just a console.log(), but it doesn't log anything which leaves me to believe that the event isn't firing.
HTML:
<div class="slot" ondrop="drop(event)" ondragover="drag(event)">
<img src="">
</div>
<img class="item" style="width: 50px; height: 50px;" draggable="true" ondragstart="drag(event)" src="flint.png">
JS:
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("img", ev.target.src);
}
function drop(ev) {
ev.preventDefault();
console.log('dropped!');
// (code to change image)
// var data = ev.dataTransfer.getData("img");
// ev.target.children[0].src = data;
}
I expected for the console to log 'dropped!', but it didn't. Can anyone help me? keep in mind that I am relatively new to Javascript and completely new to drag and drop and such.
Thank You!
Upvotes: 2
Views: 1245
Reputation: 135
So from what I gathered from the MDN, event listeners will work when you label a element as dragable so we can just add event listeners for the dragover and drop events and then it will trigger. Further you can use conditionals to determine the target was correctly chosen and then trigger a function based on that.
MDN Link: https://developer.mozilla.org/en-US/docs/Web/Events/drop
They give a really good example that does exactly what you want. I would put the example in a code snippet and play around with it. I'm sure you'll understand it in no time.
document.addEventListener("dragover", function( event ) {
// prevent default to allow drop
event.preventDefault();
}, false);
function drag(ev) {
ev.dataTransfer.setData("img", ev.target.src);
}
document.addEventListener("drop", function( event ) {
console.log("dropped")
})
.slot{
width:50px;
height:50px;
background:black;
}
<div class="slot">
<img src="">
</div>
<img class="item" style="width: 50px; height: 50px;" draggable="true" ondragstart="drag(event)" src="flint.png">
Upvotes: 2