skip to Main Content

I have a feature on a form that allows multiple uploads of images.

When you select the images you want to upload, it shows a small thumbnail of them. However, I thought it would be simple to make it so these images disappear when clicked on, but it’s not working.

See below code. The preview image click function doesn’t seem to be acknowledged and there’s no console errors to help me out. When clicked, nothing happens.

$(function() {
    // Multiple images preview in browser
    var imagesPreview = function(input, placeToInsertImagePreview) {

        if (input.files) {
            var filesAmount = input.files.length;

            for (i = 0; i < filesAmount; i++) {
                var reader = new FileReader();

                reader.onload = function(event) {
                    $($.parseHTML('<img class="preview-img">')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
                }

                reader.readAsDataURL(input.files[i]);
            }
        }

    };

    $('#upload').on('change', function() {
        imagesPreview(this, 'div.gallery');
    });

    $(".preview-img").click(function(){
        $(this).hide();
    });

});

2

Answers


  1. The reader.onload function is exectued asynchronously. So the preview image click handler is registered before the images are available in the DOM. You can verify this by registering the click handler manually via the JavaScript console after all images were rendered.

    You should use following code to set up the click event handler:

    $(document).on("click", ".preview-img", function() {
        $(this).hide();
    });
    

    This will still work after the DOM changed, since the handler is registered on the document instead of img-elements which do not exist yet.

    Login or Signup to reply.
  2. Change this line :

    $(".preview-img").click(function(){
           $(this).hide();
      });
    

    To this :

    $("body").on('click','.preview-img',function(){
        $(this).hide();
    });
    

    This event listener will detect dynamically added elements

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search