Reputation: 1365
document.getElementById('canvas_map').addEventListener(
'dragstart', function(event) {
var list_exe_selected=[];
var image_match=[];
//[...] code to find images image_match will be an htmlcollection
list_exe_selected[i]=[];
for (var j=0; j<image_match.length; j++) {
var str=image_match[j].href.baseVal;
list_exe_selected[i].push(str);
};
event.dataTransfer.setData('text', list_exe_selected);
}
document.getElementById('canvas_map').addEventListener(
'dragover', function(event) {
event.preventDefault();
});
document.getElementById('canvas_map').addEventListener(
'drop', function(event) {
var data = event.dataTransfer.getData('text');
var list_exe_selected=data.split(',');
for (var i=1; i<list_exe_selected.length; i++) {
exe_selected=list_exe_selected[i];
//do stuff
};
};
First thing: in dataTransfer.setData
text
is the data type... good. Which other data type exist??? I can't find. Is there something for array?
Second thing: my list_exe_selected
on dragstart
is something like this:
[ <1 empty space>, "my_string1", Array[2], <3 empty spaces>, "my_string2"… ]
but my data
on drop
is this:
,my_string,first_element_of_my_array,second_element_of_my_array,,,,my_string2...
my array has been 'exploded' in his elements so my list_exe_selected
do not have the same index like before and this is the problem...
Is there an easy way to resolve this problem? I could rebuild the array manually but maybe is possible to transfer the data without losing the format or is possible to pass more than one set of data...
Edit: I can be wrong but at last it look like you can't pass array directly.
Upvotes: 1
Views: 1415
Reputation: 1342
I am not familiar with event.dataTransfer
but it looks like since you're passing it text, you need to use JSON.stringify
and JSON.parse
on the array. I have modified your code to include these.
document.getElementById('canvas_map').addEventListener(
'dragstart', function(event) {
var list_exe_selected=[];
var image_match=[];
//[...] code to find images image_match will be an htmlcollection
list_exe_selected[i]=[];
for (var j=0; j<image_match.length; j++) {
var str=image_match[j].href.baseVal;
list_exe_selected[i].push(str);
};
// Turns the array into a JSON string
list_exe_selected = JSON.stringify(list_exe_selected);
// saves the array as 'text' or a string
event.dataTransfer.setData('text', list_exe_selected);
}
document.getElementById('canvas_map').addEventListener(
'dragover', function(event) {
event.preventDefault();
});
document.getElementById('canvas_map').addEventListener(
'drop', function(event) {
// gets the array as a string or 'text'
var data = event.dataTransfer.getData('text');
// formats the saved string into an array
data = JSON.parse(data);
var list_exe_selected=data.split(',');
for (var i=1; i<list_exe_selected.length; i++) {
exe_selected=list_exe_selected[i];
//do stuff
};
};
Documentation for JSON.stringify()
and JSON.parse()
.
You may also want to take a look at the MDN page for dataTransfer
.
Upvotes: 2