Frank
Frank

Reputation: 624

two js scripts blocking each other

I have a function that previews an image that is about to be uploaded:

    <script>
function readURL(input) {

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

    reader.onload = function (e) {
         var if_alternative = true;
        $('#preview_image').attr('src', e.target.result);
        //hide product_images and fileSelector
    }
    reader.readAsDataURL(input.files[0]);
  } 
}

$("#product_images").change(function(){
readURL(this);
});
</script>

Since users are able to upload more than one image, I would like the second image to be previewed as well. This is the function that is supposed to preview the second image:

<script>
function readURL(input) {

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

    reader2.onload = function (e) {
         var if_alternative2 = true;
        $('#preview_image2').attr('src', e.target.result);
    }
    reader2.readAsDataURL(input.files[0]);
 } 
}

$("#product_images2").change(function(){
readURL(this);
});
</script>

Now, the problem is that, when both scripts are active, they both preview the image in the second image container (#preview_image2), instead of previewing the first one in the first container, and the second one in the second. Can anybody tell me why? Thanks!

Upvotes: 1

Views: 105

Answers (1)

Alexis Wilke
Alexis Wilke

Reputation: 20725

The idea of using a function is to avoid duplicating code, so...

<script>
function readURL(input)
{
   var reader;

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

        reader.onload = function (e)
        {
            var id = $(input).attr("id"),
                new_id = id.substr(0, id.length - 1); // remove 's'
            $("#" + new_id).attr('src', e.target.result);
            //hide product_images and fileSelector
        };
        reader.readAsDataURL(input.files[0]);
    } 
}

$("#product_images, #product_images2").change(function()
    {
        readURL(this);
    });
</script>

Notice that variables are ALL defined at the top of a function. It is safer to define them there so you can see all the variables that you are using and avoid mixing them (not like in C/C++ where braces define a scope.)

Also, a variable defined in a parent function is available as is to the sub-functions. Quite practical.

Upvotes: 1

Related Questions