I am trying to preview photos. Whenever I click browse input and select image - image appears in HTML but when I click browse again and select another picture - first picture gets deleted and replaced with new output.innerHTML. Is there a way to keep old one and keep stacking them up? I am super new to JS, been trying to find a solution for a while but everyone suggests to use PHP and upload to DB, I could do that but I've been asked to make it only with vanillaJS.
<form id="form" method="post" onchange="loadFile(event)">
<label for="name">File name:</label>
<input type="text" id="name" placeholder="Test" value="">
<label for="description">Description:</label>
<textarea name="" id="description" cols="30" rows="5" placeholder="Alex" value=""></textarea>
<label for="file">Upload photo:</label>
<input type="text" id="browse" placeholder="No file selected" disabled>
<input type="button" value="Browse" id="loadFilesXml" onclick="document.getElementById('file').click();">
<input type="file" style="display:none;" id="file" name="file" accept="image/*">
<div class="flex">
<input type="submit" name="submit" id="submit" value="Upload">
</div>
</form>
<script>
let loadFile = function(event) {
let output = document.getElementById("gallery")
let src = URL.createObjectURL(event.target.files[0]);
output.innerHTML = "<div><img src='"+src+"'></div>"
};
</script>
You can do it like below:
<form id="form" method="post">
<label for="name">File name:</label>
<input type="text" id="name" placeholder="Test" value="">
<label for="description">Description:</label>
<textarea name="" id="description" cols="30" rows="5" placeholder="Alex" value=""></textarea>
<label for="file">Upload photo:</label>
<input type="text" id="browse" placeholder="No file selected" disabled>
<input type="button" value="Browse" id="loadFilesXml" onclick="document.getElementById('file').click();">
<input type="file" style="display:none;" id="file" name="file" accept="image/*">
<div class="flex">
<input type="button" name="submit" id="submit" value="Upload" onclick="loadFile(event);">
</div>
</form>
<div id="gallery"></div>
<script>
let loadFile = function(event){
let output = document.getElementById("gallery");
let file = document.getElementById("file");
let src = URL.createObjectURL(file.files[0]);
//output.innerHTML = "<div><img src='"+src+"'></div>";
var e = document.createElement('div');
e.innerHTML = "<img src='"+src+"'></div>";
while(e.firstChild) {
output.appendChild(e.firstChild);
}
};
</script>
Add css style(s) to beautify, resize as you please.