Add some spice to your HTML file fields with an image preview pane

posted by Ayush Newatia
10 November, 2021

The default HTML file field is rather boring. It’s quite painful to style and not really flexible either.

With a little bit of JavaScript though, we can spice up the file input field a bit and add a preview pane for images; so the user can see the image they’ve selected before submitting the form.

A good way to encapsulate the logic for this field is to use a JavaScript Custom Element. We’ll create a class called ImageInputField and define it to use the tag name image-input-field. Let’s start with our HTML markup:

  <img preview>
  <input type="file" name="logo">
  <button type="button" select>Select Image</button>
  <button type="button" remove>Remove Image</button>

The above code should be pretty self explanatory. To bring this to life, we need to create and define our custom element.

export class ImageInputField extends HTMLElement {
  connectedCallback() {
    // Configure click listeners for the two buttons
    // and a change listener for the input field

    // Hide the remove button by default as initially
    // there won't be a file selected = "none"

    // Hide the input field as it's only used under
    // the hood.
    // The user clicks on the "Select Image" button = "none"

    // Restrict the input field to images only

  get input() {
    return this.querySelector("input[type=file]")

  get selectButton() {
    return this.querySelector("button[select]")

  get removeButton() {
    return this.querySelector("button[remove]")

  get preview() {
    return this.querySelector("img[preview]")

  removeImage() {
    this.input.value = "" = "none"

  // Read the image off the disk and set it to our img element
  showPreview(image) {
    let reader = new FileReader();
    reader.onload = (event) => {


  configureListeners() {
    this.input.addEventListener('change', event => {
      let file =[0]

    this.selectButton.addEventListener('click', () => {

    this.removeButton.addEventListener('click', () => {

// Register our custom element with the CustomElementRegistry
customElements.define('image-input-field', ImageInputField)

With the above element, our component is complete. Users will now see a preview of the image they’ve selected. We’re also free to style any of the contained elements as we wish. So for example, we might want to limit the width of the image preview so a large image doesn’t mess up the layout of the whole page:

image-input-field img {
  display: block;
  max-width: 200px;

Here’s a CodePen demonstrating the component in action!