Actually I'm trying to make a form to add pictures to a gallery. The thing is, the button to add picture is wider than the preview photo so when we add the picture, we have the button in the background. I precise that I'm new in Javascript.
I've tried different ways with JS but none of them are working. If someone can tell me what did I do wrong or what I can do, it will be super great !
First here is the code for the preview :
imageInput.onchange = (evt) => {
const [file] = imageInput.files;
if (file) {
preview.src = URL.createObjectURL(file);
}
if (file != null) {
preview.style.display = "block";
}
};
const displayPreview = document.getElementById("hide");
if (file != null) {
displayPreview.style.display = "none";
}
<div id="upload">
<img id="preview" src="#" alt="Votre photo" />
<img
id="img-img"
src="assets/icons/img-vector.svg"
alt="Image d'image"
/>
<div id="hide">
<label class="file-upload">
<input accept="image/*" type="file" id="imageInput" />
+ Ajouter photo
</label>
</div>
<p>jpg, png : 4mo max</p>
</div>
You need to move the line which hides displayPreview block inside the event handler. By keeping it outside like that it would not work.
you need to do something like this below.
const displayPreview = document.getElementById("hide");
imageInput.onchange = (evt) => {
const [file] = imageInput.files;
if (file) {
preview.src = URL.createObjectURL(file);
}
if (file != null) {
displayPreview.style.display = "none";
preview.style.display = "block";
}
};
I hope this help.