3

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

Howard Renollet
  • 4,345
  • 1
  • 22
  • 30
Sjenkie
  • 187
  • 2
  • 2
  • 10

1 Answers1

11

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.

axel.michel
  • 5,716
  • 1
  • 13
  • 22