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 >
</div>
<div >
<img src="" />
</div>
CodePudding user response:
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.