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

showing an img in a div after upload

I am trying to upload an image with javascript and display it in a div but the method I’m using right now is not working. I tried using both an img tag and just setting it as a background-image but both won’t show the img in the div but when I inspect the div it shows that the URL has successfully been inserted. Where did I go wrong? Any help is appreciated. Thanks in advance.

const image_input = document.querySelector("#image_input");
image_input.addEventListener("change", function() {
  const reader = new FileReader();
  reader.addEventListener("load", () => {
    const uploaded_image = reader.result;
    $('.imgCon').attr("background-image", `url(${uploaded_image})`);
    $('.imgCon2 img').attr("src", `url(${uploaded_image})`);
  });
  reader.readAsDataURL(this.files[0]);
});
.imgCon {
  position: absolute;
  top: 30%;
  width: 40%;
  height: 40%;
  border-radius: 8px;
  background-color: #000000;
  /* background-size: 100%; */
  background-position: center;
  background-size: cover;
}

.imgCon2 {
  position: absolute;
  top: 30%;
  right: 0%;
  width: 40%;
  height: 40%;
  border-radius: 8px;
  background-color: #000000;
  /* background-size: 100%; */
  background-position: center;
  background-size: cover;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<input type="file" title="" id="image_input" accept="image/png, image/jpg">

<div class="imgCon">
</div>

<div class="imgCon2">
  <img src="" />
</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

Change to:

$('.imgCon').css("background-image", `url(${uploaded_image})`);
$('.imgCon2 img').attr("src", uploaded_image);

attr will set an attribute on the element i.e <div background-image="url(...)" and src="url(...)" is incorrect.

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