DEV Community

Ayush Newatia
Ayush Newatia

Posted on • Edited on

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

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

HTML File field

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.

HTML File field demo

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:

<image-input-field>
  <img preview>
  <input type="file" name="logo">
  <button type="button" select>Select Image</button>
  <button type="button" remove>Remove Image</button>
</image-input-field>
Enter fullscreen mode Exit fullscreen mode

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
    this.configureListeners()

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

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

    // Restrict the input field to images only
    this.input.accept="image/*"
  }

  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.preview.removeAttribute("src")
    this.input.value = ""
    this.removeButton.style.display = "none"
  }

  // Read the image off the disk and set it to our img element
  showPreview(image) {
    let reader = new FileReader();
    reader.onload = (event) => {
      this.preview.setAttribute("src", event.target.result)
    }

    reader.readAsDataURL(image);
    this.removeButton.style.removeProperty("display")
  }

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

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

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

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

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;
}
Enter fullscreen mode Exit fullscreen mode

Here's a CodePen demonstrating the component in action!Β 

Top comments (2)

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
ayushn21 profile image
Ayush Newatia

That's a bit weird .... I think what could be happening is the document hasn't been written when the component is initialized .... maybe try adding defer to your script tag and see if that does anything?