I am trying to have each div display a different uploaded image but when I try uploading a picture with the second div it instead changes the first div's picture and nothing happens to the second div.
<div class="user-img">
<img src="./images/image.jpg" alt="Avatar" id="photo">
<input type="file" id="file" accept="image/*">
<label for="file" id="uploadbtn"><i class="fas fa-camera"></i></label>
</div>
<div class="user-img">
<img src="./images/image.jpg" alt="Avatar" id="photo">
<input type="file" id="file" accept="image/*">
<label for="file" id="uploadbtn"><i class="fas fa-camera"></i></label>
</div>
<script>
const img = document.querySelector('#photo');
const file = document.querySelector('#file');
file.addEventListener('change', function(){
const chosenFile = this.files[0];
if(chosenFile){
const reader = new FileReader();
reader.addEventListener('load', function(){
img.setAttribute('src',reader.result);});
reader.readAsDataURL(chosenFile);
}
});
</script>
You can't have two elements with the same ID of file and Photo. ID's Should be unique. In this case you should utilize classes instead.
Then use document.getElementsByClassName() to receive an array of elements which you can iterate through and add the event listener to the file elements.
Change your <img> elements to use class names, rather than id's. Ex:
<img src="./images/image.jpg" alt="Avatar" class="photo">
Next grab your images using a document.getElementsByClassName() call like the following
const imgs = document.getElementsByClassName('photo');
Then you can loop through the imgs array and set the src attribute, like so
imgs.forEach((img) => {
img.setAttribute('src', reader.result);
});