0
<input hidden type="file" id="inpfile" accept="image/*">

$('#inpfile').change(function(){
    var a = this.files[0];
    var reader = new FileReader();
    reader.readAsDataURL(a);
    reader.onload = function (e) {
        var imga = new Image();
        imga.src = e.target.result;
    }
});

Where is that image? How can I really get it on screen and change its style?

6
  • You can append a img tag (wherever you want that image). And attribute src with value e.target.result Commented Apr 23, 2018 at 7:53
  • You need to append it an element. Something like document.body.appendChild(imga) Commented Apr 23, 2018 at 7:53
  • Where is that image? why did you put hidden? Commented Apr 23, 2018 at 7:55
  • @לבנימלכה, input is hidden, but not the image. Commented Apr 23, 2018 at 7:59
  • 1
    I know it's not your problem here, but don't use a FileReader for displaying a user inputted media in your page. Instead use URL.createObjectURL which will use far less memory and code / callback nightmares. Commented Apr 23, 2018 at 8:36

1 Answer 1

2

When you do new Image() you create element in memory only, not in DOM. Create element <img> in DOM and use it instead

$(document).ready(function(){
var currentIndex = 1;
$('#inpfile').change(function(){
    var reader = new FileReader();
    reader.readAsDataURL(this.files[0]);
    reader.onload = function (e) {
        $('<img id="img' + currentIndex + '" class="img">') // jQuery will create new element if you pass not CSS selector, but expression, like in this case. Element still in memory
        .attr('src', e.target.result) // Change src attribute of element to base64 encoded image source
        .appendTo('.gallery'); // Append previous created element to <div class="gallery"> in DOM
        currentIndex++; // Increment ID counter, so each element has unique ID
    }
});
});
.img {
  width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="inpfile" accept="image/*"/>
<div class="gallery"></div>

Sign up to request clarification or add additional context in comments.

9 Comments

can I set id instead of class and select it by id to change its style?
@puerto Yes if it's the only element with this id on page.
how can I do that, pls
$('#img') instead $('.img')
# means id and . means class
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.