Image preview

Asked

Viewed 71 times

1

I’m making a preview, and it’s happening like this, I want it to not appear as if it had no image, and only appear the preview image when the user chooses the image.

It’s getting like this before I put the image, but I want it not to have this shape without image:

inserir a descrição da imagem aqui

Code:

Javascript

var loadFile = function(event) {
     var output = document.getElementById('output');
     output.src = URL.createObjectURL(event.target.files[0]);
}

HTML that takes the image and shows

<img id="output" style="width:100%;height:250px;padding:10px 10px 10px 10px;"/>
<br>
<br>
<input type="file" name="img" id="img" accept="image/jpg, image/jpeg, image/png" onchange="loadFile(event)"/>
<br/><br/>

2 answers

0

You can leave as the default image a path to an explanatory image (something like: "Select your file") or even a clear 1x1 gif.

This way will show that image until the user selects from it.

<img src="sem-imagem.jpg" id="output" style="width:100%;height:250px;padding:10px 10px 10px 10px;"/>
<br>
<br>
<input type="file" name="img" id="img" accept="image/jpg, image/jpeg, image/png" onchange="loadFile(event)"/>
<br/><br/>

Or even hide the image until something has been selected, but I find the first option more interesting.

  • I tried to do this, but it turns out that this is in Laravel

  • and then you’re not accepting when I try to put an img

  • What if you put it in javascript? when you start the document change the image’s SRC? If it doesn’t work I think you’ll have to really hide the image, maybe with a CSS class and then when you set the output SRC add also to the output the class that would make the image visible or just a display:block;. Do you understand what I mean? I don’t know if it’s possible in the Atlantic to do this, I have little experience with it.

0


You can leave the image without opacity by adding opacity: 0 style:

<img src="sem-imagem.jpg" id="output" style="opacity: 0; width:100%;height:250px;padding:10px 10px 10px 10px;"/>

In the function, change the opacity to 1:

var loadFile = function(event) {
    var output = document.getElementById('output');
    output.src = URL.createObjectURL(event.target.files[0]);
    output.style.opacity = "1";
}

Or you can use visibility: hidden and change the function to visibility: visible:

In function:

var loadFile = function(event) {
    var output = document.getElementById('output');
    output.src = URL.createObjectURL(event.target.files[0]);
    output.style.visibility= "visible";
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.