Reputation: 1
I am writing a code to add multiple images to a DIV one after another by clicking a button. The code is below. In this case the image is getting replaced, however, I want the older image to remain and new image to be appended.
<html>
<body>
<form>
<input id="inp" type='file'/>
<div id="placehere"></div>
</form>
</body>
</html>
<script language ="javascript">
var elem = document.createElement("img");
elem.setAttribute("height", "150");
elem.setAttribute("width", "150");
elem.setAttribute("alt", "Flower");
function readFile() {
if (this.files && this.files[0]) {
var FR = new FileReader();
FR.addEventListener("load", function (e) {
document.getElementById("placehere").appendChild(elem);
elem.src = e.target.result;
});
FR.readAsDataURL(this.files[0]);
}
}
document.getElementById("inp").addEventListener("change", readFile);
</script>
How do I add the new image instead of replacing the existing one?
Upvotes: 0
Views: 222
Reputation: 1369
function readFile() {
if (this.files && this.files[0]) {
var elem = document.createElement("img");
elem.setAttribute("height", "150");
elem.setAttribute("width", "150");
elem.setAttribute("alt", "Flower");
var FR = new FileReader();
FR.addEventListener("load", function(e) {
document.getElementById("placehere").appendChild(elem);
elem.src = e.target.result;
});
FR.readAsDataURL(this.files[0]);
}
}
document.getElementById("inp").addEventListener("change", readFile);
<form>
<input id="inp" type='file' />
<div id="placehere">
</div>
</form>
The problem with your code was you will have to create the image tag every time user uploads a file. That's why I have moved below code inside readFile() function :-
var elem = document.createElement("img");
elem.setAttribute("height", "150");
elem.setAttribute("width", "150");
elem.setAttribute("alt", "Flower");
Upvotes: 2
Reputation: 1
The reason the image is being replaced is because on every call to readFile
you are reusing the same img element that you created on the initial load of the script (var elem = document.createElement("img")
).
The solution is to move the document.createElement call into the readFile function causing you to create a new image element on every every call. See below for revised code. Hope this helps!
function readFile() {
if (this.files && this.files[0]) {
var FR = new FileReader();
FR.addEventListener("load", function(e) {
var elem = document.createElement("img");
elem.setAttribute("height", "150");
elem.setAttribute("width", "150");
elem.setAttribute("alt", "Flower");
document.getElementById("placehere").appendChild(elem);
elem.src = e.target.result;
});
FR.readAsDataURL(this.files[0]);
}
}
document.getElementById("inp").addEventListener("change", readFile);
Upvotes: 0