How can I display an image and text from an array on a webpage? Ask Question code example

Example 1: How can I display an image and text from an array on a webpage? Ask Question

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <h1>My images</h1>
    <input id="fileInput" type="file" accept="image/*" multiple="false" value="Select image">
    <input id="button" type="button" value="Add image and redraw">

    <div>
        <input id="artistField" type="text" placeholder="artist">
        <input id="titleField" type="text" placeholder="title">
    </div>

    <hr>
    <div id="myImages">
    </div>


    <ul></ul>

    <script src="album.js"></script>
  </body>
</html>

Example 2: How can I display an image and text from an array on a webpage? Ask Question

var info = {
    myImages: [],

    addImage: function(imageBlob) {
        this.myImages.push(imageBlob);
    },

    addInfo: function(artist, title) {
        this.myImages.push({
            artist: artist, 
            title: title
            });
    },


    redrawImages: function() {
        var divForImages = document.getElementById('myImages');
        divForImages.innerHTML = '';
        this.myImages.forEach((imageBlob) => {
            var img = document.createElement('img');
            img.style.width = "200px";
            img.style.height = "200px";
            img.src = URL.createObjectURL(imageBlob);
            divForImages.appendChild(img);
        });

    },

    redrawInfo: function() {
        var ul = document.querySelector('ul');
        this.myImages.forEach(function (item) {
            let li = document.createElement('li');
            ul.appendChild(li);
            li.innerHTML += item;
        });
    }


}

var handlers = {
    addImageAndRedraw: function() {
        var fileInput = document.getElementById('fileInput');
        var artistField = document.getElementById('artistField');
        var titleField = document.getElementById('titleField');

        if (fileInput.files.length === 1) {
            info.addImage(fileInput.files[0]);
            info.addInfo(artistField.value, titleField.value);
            info.redrawImages();
            info.redrawInfo();
        }
    }
}

var button = document.getElementById('button');
button.addEventListener('click', handlers.addImageAndRedraw);