Lucfia Lucfia - 5 months ago 23
jQuery Question

Multiple event listeners for a class

I am trying to make multiple drag and drop areas. I am trying to add listeners for a "drop-zone" class (for every element with this class).

var dropZone = document.getElementById('some_area'); // ok
// var dropZone = document.getElementByClassName('drop-zone'); // not working

dropZone.addEventListener('dragover', function(e) {
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
});

dropZone.addEventListener('drop', function(e) {
var target_img = $(this).find('img');
e.stopPropagation();
e.preventDefault();
var files = e.dataTransfer.files; // Array of all files
for (var i=0, file; file=files[i]; i++) {
if (file.type.match(/image.*/)) {
var reader = new FileReader();
reader.onload = function(e2) { // finished reading file data.
var img = document.createElement('img');
img.src= e2.target.result;
target_img.attr('src',e2.target.result);
target_img.addClass('full-preview');
}
reader.readAsDataURL(file); // start reading the file data.
} } });

Answer

You need to query for all elements that have the specific class.

// Returns a list of the elements within the document 
// that match the specified 'drop-zone' class.   
var dropZones = document.querySelectorAll('.drop-zone');


for (var i = 0; i < dropZones.length; i++) {
  // Add the event listeners for each element of the list.
  dropZones[i].addEventListener('dragover', function (e) {
    // ...
  });

 dropZones[i].addEventListener('drop', function (e) {
   // ...
 });
}