I am trying to create a web-app which allows the user to upload an image from their pc, and from that, it will create an object, and add it into an array (to have record of it and its properties) and also display it on screen.
I have created a codepen: https://codepen.io/eve_mf/pen/XebVWv
html:
<form id="form" action="" method="post" enctype="multipart/form-data">
<div class="file-uploader-wrapper">
<input id="file-uploader" class="file-uploader-input" type='file' onchange="retrieveImageFromUpload(this);"/>
<button class="file-uploader-btn" type="button">Select an image</button>
</div>
</form>
<div id="map-view"></div>
js:
let allImages = [];
let displayImages = document.getElementById("map-view");
let imagesCounter = 0;
$(".file-uploader-btn").click(function() {
$("#file-uploader").click();
});
function retrieveImageFromUpload() {
let imgReader = new FileReader();
imgReader.readAsDataURL(document.getElementById("file-uploader").files[0]);
imgReader.onload = function (imgReaderEvent) {
let imageUploadedName = imgReaderEvent.target.result;
return readUploadedImage(imageUploadedName);
};
}
//create HTML image from the uploaded img
function readUploadedImage(imageUploadedName) {
imagesCounter++;
let img = document.createElement('img');
img = {
"id": 'screen-' + imagesCounter,
"src": imageUploadedName,
"alt": 'Default-alt'
};
allImages.push(img);
console.log(allImages);
var imgHTML = img.cloneNode(true);
imgHTML = "<img id='"+ img.id + "' src='" + img.src + "' alt ='" + img.alt + "' />";
displayImages.appendChild(imgHTML);
console.log("-------------");
}
My problem begins after creating the image element; I think I am getting confused but I can not really understand where or why.
- I create an image with "let img = document.createElement('img');"
- Then, I set its properties as object, and I think it is here where I get messed up. Then, I put this object into my array (called allImages), so, this is what I want so far.
- But then, a part from adding this object into my array, I want to display it as an HTML image, I am trying this with "appendChild", But definitely is something really wrong because I get the error that I am not operating with a node element.
Can someone give me a push to the right path?
Thank you