Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Uncaught TypeError: Cannot read properties of undefined (reading 'files')

I do not know why this error occurs when the change event run on the function. Could you tell what is the issue please ?

function clickEvent(event) {
  this.childNodes.forEach(function(node) {
    if (node && node === event.target && node.nodeType === 1) {
      node.children[1].click();
    }
  });
}

function changeEvent(event) {
  this.childNodes.forEach(function(node) {
    if (node && event.target.files.length) {
      console.log(event.target.dataTransfer.files[0])
    }
  });
}


function eventHandler(element, eventType, callback) {
  return document.getElementById(element).addEventListener(eventType, callback, false);
}

eventHandler('app', 'click', clickEvent);
eventHandler('app', 'change', changeEvent);
#app {
  display: grid;
  grid-template-columns: repeat(auto-fill, 200px);
  padding: 24px;
  gap: 24px;
}

.drop-area {
  width: 200px;
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-sizing: border-box;
  padding: 8px;
  border: 2px dashed #cccccc;
  border-radius: 10px;
}

.drop-area__prompt {
  pointer-events: none;
}

.drop-area__input {
  display: none;
}
<div id="app">
  <div id="1" class="drop-area">
    <span class="drop-area__prompt">Click here</span>
    <input type="file" accept="image/*" class="drop-area__input" name="upload"> </div>
  <div id="2" class="drop-area">
    <span class="drop-area__prompt">Click here</span>
    <input type="file" accept="image/*" class="drop-area__input" name="upload"> </div>
</div>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You are seeing that error because dataTransfer does not exist on the target object for your file events.

JS Error Log

event.dataTransfer is a thing but only for drag and drop events

You can fix your code by changing this line from

console.log(event.target.dataTransfer.files[0])

to

console.log(event.target.files[0])

Here are the logs after this fix:

JS Logs after change

Here is a JS Fiddle with the updated code.

Hope this helps!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading