Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu January 19, 2024 › #HowTo #image

How to display multiple images in HTML using JavaScript?

In this article, we'll cover how to allow users to upload multiple images and display a preview of those images in an HTML webpage using JavaScript.

We'll use the HTML <input> element with the multiple attribute to enable multiple file selection and JavaScript to handle the preview.

How to Select and Preview Multiple Images using JavaScript#

To achieve this, we'll create an HTML form with an <input> element of type file that accepts multiple files. Then, we'll use JavaScript to handle the selected files and display their previews.

<style>
 .preview-image {
      width: 150px;
      height: 150px;
      margin: 5px;
    }
</style>
<input type="file" id="imageInput" accept="image/*" multiple>
<div id="imagePreview"></div>
<script>
  const imageInput = document.getElementById('imageInput');
  const imagePreview = document.getElementById('imagePreview');

  imageInput.addEventListener('change', function () {
    imagePreview.innerHTML = '';
     const files = imageInput.files;

       for (const file of files) {
          const reader = new FileReader();

          reader.onload = function (e) {
               const imgElement = document.createElement('img');
               imgElement.src = e.target.result;
               imgElement.className = 'preview-image';
               imagePreview.appendChild(imgElement);
           };

            reader.readAsDataURL(file);
          }
    });
</script>
Try it Yourself »

Explanation of the above example:

  1. We create an <input> element with the file type and the multiple attribute to allow multiple file selection.
  2. The accept attribute limits the file types to images.
  3. We use JavaScript to handle the change event of the input element.
  4. Inside the event listener, we clear previous previews and loop through the selected files.
  5. For each file, we create a FileReader object to read its content as a data URL.
  6. We create an <img> element for each file, set its src attribute to the data URL, and append it to the imagePreview div.

Conclusion #

In this article, you've learned how to enable users to upload and preview multiple images in an HTML webpage using JavaScript.

This feature is useful for various applications, such as image galleries and user profile picture uploads. Users can select multiple images and the previews will be displayed dynamically on the page.

save
listen
AI Answer
Write Your Answer
loading
back
View All