0

Please note, I understand that below code is far from poetry and I'm beginner. With this in mind, I have following html inside a <form>:

<div class="image-upload">
 <img id="send_photo_img1" src="assets/images/index2.png"/>
 <input id="send_photo_input1" type="file"/>
 <img id="send_photo_img2" src="assets/images/index2.png"/>
 <input id="send_photo_input2" type="file"/>
</div>

Goal: once user clicks image (index2.png, which is a placeholder with "+" sign), window opens like from input=file, user chooses img and it gets loaded instead of the placeholder.

Rest of the code:

Jquery (based on @Ivan Bayev's answer here, while his code it so good, mine got quite clumsy atm..)

function readURL(input) {

 if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function (e) {
        $('#send_photo_img1').attr('src', e.target.result);
    }

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

$("#send_photo_img1").click(function(){
    $("#send_photo_input1").trigger("click");
    $("#send_photo_input1").change(function(){
        readURL(this);
    });         
});

CSS

.image-upload > input
{
    display: none;
}

It works. But: (1) I feel jQuery is really bad and (2) biggest concern - once image is displayed instead of the placeholder, I still have "loading" sign for like 30-40 seconds. Then it is gone.

Any advise is highly appreaciated. Thanks!

Zerus
  • 158
  • 13

1 Answers1

0

Just in case anyone is interested on a solution of above, here it is.

First of, above code is attached to ID's, which is bad if many instances of input=file are on single page. So first reattached this to classes. Each block would look like:

<div class="img_upload">
 <img class="send_photo_img" src="assets/images/index2.png"/>
 <input class="send_photo_input" type="file"/>
</div>

Then it takes some workaround to select that via jQuery:

$(".img_upload img").click(function(){
    var imgDiv = $(this).next(".send_photo_input");
    imgDiv.trigger("click");
    imgDiv.change(function(){
        //console.log('Display that to trace results');
        //your function here.
    });
});

CSS:

.img_upload input
{
    display: none; // hide original input
}
.img_upload img
{
    width: 90px;
    height: 90px;
    cursor: pointer;
}

The ReadURL function in my question actually works perfect, just change this:

reader.onload = function (e) {
    $('#send_photo_img1').attr('src', e.target.result);
}

to this:

reader.onload = function (e) {
   $(input).prev(".send_photo_img").attr('src', e.target.result);
}

And note that I use prev(), while you could use more general:

 $(input).parent().find(".send_photo_img").attr('src', e.target.result);

Note that you can use an icon instead of img for better effect.

This answer is just to give you idea of working code for above question. Feel free to ask other details if needed.

Zerus
  • 158
  • 13