Home > Net >  Display different images on the same web page
Display different images on the same web page

Time:09-26

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 >
    <img src="./images/image.jpg" alt="Avatar" id="photo">
    <input type="file" id="file" accept="image/*">
    <label for="file" id="uploadbtn"><i ></i></label>
</div>
<div >
    <img src="./images/image.jpg" alt="Avatar" id="photo">
    <input type="file" id="file" accept="image/*">
    <label for="file" id="uploadbtn"><i ></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>

CodePudding user response:

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.

CodePudding user response:

Change your <img> elements to use class names, rather than id's. Ex:

<img src="./images/image.jpg" alt="Avatar" >

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);
});
  • Related