user2127833
user2127833

Reputation: 181

How to remove image preview when cleared?

I have a program where a selected image is previewed. Here is the code I use.

Javascript

function readURL(input) {

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

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

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

    $("#uploadphoto").change(function(){
        readURL(this);
        $('#preview').show();
    }); 

But when I remove it with this:

$('#preview').on("click", function () {
     $('#uploadphoto').replaceWith( selected_photo = $('#uploadphoto').clone( true ) );
     $('#preview').attr('src', '');
});

The photo still is displayed. When I submit the page the photo is not submitted, which I wanted, but how do I get rid of the preview image? $('#preview').attr('src', ''); didn't seem to work...?

Upvotes: 0

Views: 1821

Answers (1)

adeneo
adeneo

Reputation: 318362

You'd use removeProp() for that, as just changing the attribute isn't enough:

function readURL(input) {

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

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

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

$("#uploadphoto").change(function () {
    readURL(this);
    $('#preview').show();
});

$('#preview').on("click", function () {
    $('#uploadphoto').replaceWith(selected_photo = $('#uploadphoto').clone(true));
    $('#preview').removeProp('src').hide();
});

FIDDLE

You should also hide and show the image, to make sure the "empty image" icon doesn't show, or you could just remove the element all together and insert a new one each time.

EDIT:

To fade the image out, do:

$('#preview').on("click", function () {
    $('#preview').fadeOut(1000, function() {
        $(this).removeProp('src');
        $('#uploadphoto').replaceWith(selected_photo = $('#uploadphoto').clone(true));
    });
});

Upvotes: 2

Related Questions