Search code examples
javascripthtmlcssp5.jsinput-type-file

Replace CHOOSE FILE with an image


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.


Solution

  • 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>