I'm a complete beginner and just started teaching myself code a couple days ago, so if this is not the right way to do it, feel free to let me know how you would do it instead.
I am trying to upload multiple images onto a webpage using javascript. So far, I have been able to save the data URL to local storage, but every time I select a new file, the saved URL get overwritten. Then, when I click "Choose File," all of the images become the same. Is there a way to save the data URL with unique names without having to change it in javascript every time?
HTML:
<!DOCTYPE html>
<html>
<head>
<title>||Working with elements||</title>
</head>
<body>
<div id="div1">The text above has been created dynamically.</div>
<div>
<label for="name"></label>
<input type="file" id="name">
</div>
</body>
<script src="test.js">
</script>
</html>
JS:
window.addEventListener('load', function() {
document.querySelector('input[type="file"]').addEventListener('change', function() {
if(this.files && this.files[0]) {
const x = document.querySelector('img');
x.src = URL.createObjectURL(this.files[0]);
}
});
});
document.querySelector("#name").addEventListener("change", function() {
const reader = new FileReader();
reader.addEventListener("load", () => {
sessionStorage.setItem("recent-image", reader.result);
});
reader.readAsDataURL(this.files[0]);
});
document.body.onclick = addElement;
function addElement () {
// create a new div element
const newDiv = document.createElement('img');
const nameInput = document.querySelector('#name');
document.addEventListener("click", () => {
const recentImageDataURL = sessionStorage.getItem("recent-image");
if (recentImageDataURL) {
newDiv.setAttribute("src", recentImageDataURL);
}
});
const currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
}