I am making a whack the mole game with Vanilla JS and I am trying to make the person whack whatever he wants by letting them upload an image by input file but even after days of searching for any type of solution I had no luck.
HTML:
<input type='file' id='getval' name="background-image" />
<div >
<div >
<img >
</div>
<div >
<img >
</div>
</div>
Javascript Vanilla:
document.getElementById('getval').addEventListener('change', readURL);
function readURL() {
let file = document.getElementById("getval").files[0];
document.getElementsByClassName('mole')[0].setAttribute("style", "background-image: url(" file ")");
}
CSS:
.mole {
background-image: url('');
}
The game works fine but the image uploaded does not appear:
If anyone could help me with this I will be more than welcome.
These project is part of #javascript30. I recreate them and change parts of it to practice Vanilla JS but I have been stuck for days with this one.
CodePudding user response:
You can use something like this.
https://www.w3docs.com/learn-javascript/file-and-filereader.html
https://developer.mozilla.org/en-US/docs/Web/API/FileReader
const fileInput = document.getElementById('imageInput');
const images = document.querySelectorAll('.mole');
fileInput.addEventListener('change', (e) =>{
const file = e.target.files[0];
let fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = function (){
images[0].setAttribute('src', fileReader.result);
// images[0].setAttribute('style', `background-image: url('${fileReader.result}')`);
}
})
body {
min-height: 100vh;
margin: 0;
background-color: bisque;
display: grid;
place-content: center;
}
.box{
display: flex;
flex-direction: column;
place-content: center;
align-items: center;
}
input{
margin-bottom: 1rem;
}
.images{
display: flex;
flex-direction: row;
}
.mole {
width: 10rem;
height: 10rem;
margin-bottom: 1rem;
}
<div >
<input type="file" id="imageInput" />
<div >
<img />
<img />
</div>
</div>