Reputation: 4987
I would like to check to see if an item with id === itemId is dropped on a droppable element, using native Drag and Drop.
function dragDrop(itemId){
var droppable = document.querySelector('#droppableElement');
addEvent(droppable, 'drop', function(e){
if (e.preventDefault){
e.preventDefault();
}
// How do I check that the id of the dropped item === itemId
if (e.dataTransfer.getData('id') === itemId){
alert('Successfuly dropped item with id = ' itemId + '.');
}
});
}
draggableItem = document.querySelector('#draggable');
dragDrop(draggableItem);
The comment is where I need help. This link was my point of departure. http://html5doctor.com/native-drag-and-drop
Upvotes: 2
Views: 2157
Reputation: 1014
When the ondragstart
event is fired, you should set the dataTransfer's data to the id of the element that you're transferring. So, your code would be:
function dragDrop(itemId){
var droppable = document.querySelector('#droppableElement');
addEvent(droppable, 'drop', function(e){
if (e.preventDefault){
e.preventDefault();
}
if (e.dataTransfer.getData('id') == itemId){
alert('Successfuly dropped item with id = ' itemId + '.');
}
});
}
draggableItem = document.querySelector('#draggable');
addEvent(draggableItem, "dragstart", function(e) {
e.dataTransfer.setData('id', this.id);
});
dragDrop(draggableItem.id);
Sources: HTML5 Doctor
Upvotes: 2