Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: show selected image [duplicate]

I was trying to make it so when you select your image it will show it directly. Ofcourse you do this in a onchange thing in html. This is what i have by now:

function showImage(src, target) {
    var fr = new FileReader();

    fr.onload = function (e) { target.src = this.result; };

    src.addEventListener("change", function () {

        fr.readAsDataURL(src.files[0]);
    });

}
function putImage() {
    var src = document.getElementById("select_image");
    var target = document.getElementById("target");
    showImage(src, target);
}
<img id="target" />
<input type="file" id="select_image" name="image" onchange="putImage()"> </input>

This works not for me in a weird way. Because the onchange works. I can test that by alerting something on the event. That works great. The javascript works too in a jsfiddle.. But these things combined not. I hope someone can help

like image 986
Sjenkie Avatar asked Jul 04 '26 17:07

Sjenkie


1 Answers

You don't need the change event inside the showImage function. You already call the putImage method with the onechange event handler inside the html, and that method contains the call of showImage:

function showImage(src, target) {
    var fr = new FileReader();
    fr.onload = function(){
        target.src = fr.result;
    }
    fr.readAsDataURL(src.files[0]);
}

function putImage() {
    var src = document.getElementById("select_image");
    var target = document.getElementById("target");
    showImage(src, target);
}

fiddle is here.

like image 59
axel.michel Avatar answered Jul 07 '26 07:07

axel.michel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!