0

Hi I am trying to replace the choose file button with an image. I am using javascript to create the button but when I am inspecting the website, it shows me a html script of the button which is of type= file.

To create it, I used:

input = createFileInput(handleFile);
    input.elt.style["width"] = "40%";
    input.elt.style["font-size"]="3vmin";

function handleFile(file) {
    print(file);
    if (file.type === 'image') {
        imgFile = file.data;
        img = createImg(file.data);
        img.hide();
        canvas.image(img, 0, 0, 224, 224);
        image(img, 0, 0, width, height/2);
        img.remove();
    }
    mode = 1;
    tint = false;
}

Can anyone suggest how I can change the generic button with an image.

Rocky Johanson
  • 147
  • 1
  • 1
  • 9
  • I am not sure if you can change the button to an image, but one approach I used in the past was to create an invisible button. Then, in the click event of the image, trigger a click in the file input button. – Bruno Monteiro Sep 29 '19 at 20:18
  • Possible duplicate of [Replace input type=file by an image](https://stackoverflow.com/questions/2855589/replace-input-type-file-by-an-image) – weegee Sep 29 '19 at 20:20
  • @weegee I have been through this solution but none of them were a successful solution to me. – Rocky Johanson Sep 29 '19 at 20:26
  • @RockyJohanson then you should mention that in the question, what didn't work and what you tried. Clearly nothing there matches with your approach. Did you try every answer there? – weegee Sep 29 '19 at 20:29
  • @weegee I tried including those approaches in the html file but it just creates another generic button – Rocky Johanson Sep 29 '19 at 20:33

1 Answers1

0

I think you can cheat and position an image over the input, then add a click handler to the image and pass it through to the input button below.

Is this what you are trying to achieve?

const input = document.querySelector("#avatar");
const button = document.querySelector("#button");

button.addEventListener('click', event => input.click(event));
.body {
  font-family: sans-serif;
}

label {
  display: inline-block;
  padding: 1em 0;
}

.wrapper {
  position: relative;
}

#avatar {
  display: block;
  height: 50px;
  border: 1px solid #333;
}

#button {
  position: absolute;
  left: 1px;
  top: 1px;
}
<div class="body">
  <label for="avatar">Choose a profile picture:</label>
  <div class="wrapper">
    <input type="file" id="avatar" name="avatar">
    <img id="button" src="https://via.placeholder.com/75x50/333333/ffffff?text=Avatar"></img>
  </div>
</div>
Will
  • 3,201
  • 1
  • 19
  • 17