Abax
Abax

Reputation: 54

Hybrid/double file entry for image

I have this javascript code below, where i want to make a hybrid entry method for an image file: dropping it and selecting by the file explorer.

The drop work perfectly, but if you try to upload a file using file explorer it doesn't show. I think is something inside imgLoad() because is not loading when i run it in the change event, no matter how i putted (even using different function call methods).

var obje=document.getElementById('toDrop');
var fileDoor=document.getElementById('fileImg');
obje.ondragover=function(ev) { ev.preventDefault();}
obje.ondrop=function imgLoad(eve) {
  eve.preventDefault();
  var fil=new FileReader();
  fil.onload=function(ev) { document.getElementById('toDrop').style.backgroundImage="url('"+ev.target.result+"')";
 }
   fil.readAsDataURL(eve.dataTransfer.files[0]);
  }
  fileDoor.onchange=imgLoad();

Demo here: https://jsfiddle.net/vtsvr4sa/1/

Upvotes: 1

Views: 40

Answers (1)

guest271314
guest271314

Reputation: 1

imgLoad is not a globally defined function at Javascript at Question. You are also calling imgLoad immediately at fileDoor.onchange=imgLoad() instead of referencing the function fileDoor.onchange=imgLoad.

change event does not have a .dataTransfer property. Handle both event.dataTransfer.files or event.target.files within imgLoad handler using OR || operator.

Adjust HTML to use <input type="file"> element as drop event target. Set <input type="file"> element CSS to same width and height as parent element, opacity to 0, and position to absolute, with top set to parent element .ingConf top value

<!DOCTYPE html>
<html>

<head>
  <style>
.imgConf {
  height: 150px;
  width: 150px;
  border-radius: 100%;
  margin: 20px;
  background-size: 100% 100%;
  text-align: center;
  background-repeat: no-repeat;
  background-size: 100% 100%;
}

.imgConf>label {
  font-size: 15px;
  background-color: rgba(255, 250, 205, 0.5);
  margin-top: 40%;
  width: 80px;
  border-radius: 3px;
}

.imgConf input {
  top: 0;
  opacity: 0;
  width: 150px;
  height: 150px;
  display: block;
  position: absolute;
}
  </style>
</head>

<body>
  <div class='imgConf' id='toDrop'>
Click or drop image here
<input type="file" accept="image/*" id='fileImg' name="profilePh">
  </div>
  <script>
var obje = document.getElementById('toDrop');
var fileDoor = document.getElementById('fileImg');

function imgLoad(eve) {
  var fil = new FileReader();
  fil.onload = function(ev) {
    obje.style.backgroundImage = `url(${ev.target.result})`;
  }
  fil.readAsDataURL(eve.target.files[0] || eve.dataTransfer.files[0]);
}
fileDoor.onchange = imgLoad;
fileDoor.ondrop = imgLoad;
fileDoor.ondragover = function(e) {
  e.preventDefault()
}
  </script>
</body>

</html>

Upvotes: 1

Related Questions