I am a new programmer. I’m trying to make an upload image function, but the image isn’t showing up. This is what I have for the HTML and Javascript.
<!-- Title -->
<h2 id="cyor-h2">Create your own Recipe</h2>
<img id="food-image" class="square-recipe-img" style="display:none;" src="no-image.jpg">
<button id="cyor-button" onclick="createButton()">Begin</button>
<!-- Select Image -->
<button><label for="image_input">Update Image</label></button>
<input style="display:none;" type="file" accept="image/png, image/jpeg, image/jpg, image/webp" id="image_input">
<script>
let foodImage = document.getElementById("food-image");
let inputFile = document.getElementById("image_input");
inputFile.onchange= myFunction()
function myFunction() {
foodImage.src = URL.createObjectURL(inputFile.file[0]);
}
</script>
`
2
Answers
i Hope this helps your cause, for a simple file Upload functionality using js, you can use
FileReader
API in js, and its quite simple. the input fields that you have created is exactly what we are going to use, the only difference is that we are going to introduce achange
event which changes the src of image from thatimg
tag with the one that reader just interpreted.I wasnt sure what you’re gonna do with that
Begin
button so i deleted it in my code.Check out the snippet for the implementation.
There are three problems:
inputFile.onchange = myFunction()
having the parenthesis will make the function get invoked immediately when the script runs but not when the event is invoked. Instead, use thisinputFile.onchange = myFunction
this will allow the function to be invoked when the event occurs.After fixing the first problem, you need to use the
files
property notfile
. You need to make this modificationfoodImage.src = URL.createObjectURL(inputFile.file[0])
Finally, make sure you change the
style = display:none
property to something likeblock
fromnone
. You can do this by adding this within your function like so:foodImage.style.display = "block";
Your modified file should look something like this:
though a better way would be to do this: