Search code examples
functionloopsparametersblob

Loop Through A Function Parameter / Images Created With A `new Image()` Instance


I have an image thumbnail that is created using new Image() which essentially shows thumbnails of images that are to be uploaded prior to form submission.

I have PHP validations that handle the uploads on the backend. If an image is less than 4 MB the image uploads fail in the backend and I would like to append a message to the particular thumbnail in regard to this with javascript.

The function below is called within the form with an oninput attribute and takes a parameter file.

The Problem

Because I'm essentially looping through the file parameter, I can't work out how to loop the images created by the new Image() instance each time, so it only shows the error on the relevant image.

Any help much appreciated.

function updateThumbnail(file) {
    if (file.type.startsWith('image/')) {

        let 
        uploadImageWrapper = document.createElement('figure'),
        thumbnailElement = new Image();
    
        // image thumbnail
        thumbnailElement.classList.add('drop-zone__thumb')
        thumbnailElement.src = URL.createObjectURL(file)
    
        // appending elements
        showSelectedImages.append(uploadImageWrapper) // <figure> element
        uploadImageWrapper.append(thumbnailElement) // image thumbnail

        // error messaging for file size
        let thumbnails = document.querySelectorAll('.drop-zone__thumb'),
        sizeError = `<p>Image must be bigger than 4MB</p>`

        thumbnails.forEach(img => {
            if (img.size < 4000000) {
                img.insertAdjacentHTML('afterend', sizeError)
            }
        })

        console.log(img.size)
        console.log(thumbnailElement)

    }

} // end of 'updateThumbnail' function

// ---  updateThumbnail(file) is called in the HTML with an `oninput` attribute in the form

Solution

  • The function handles one image file and adds a thumbnail for it, so why not handle the sizeError only for that image file at that time.

    Just do:

    if (file.size < 4000000) {
      thumbnailElement.insertAdjacentHTML('afterend', sizeError);
    }
    

    and remove the thumbnails variable and the code around.