Let's take a selfie - The capture attribute

You may know the input type="file", but did you know there is a capture attribute which lets you define what should be used to capture that new media? In this article you will learn how to use the capture attribute to capture media directly from your device.

The capture attribute #

There are two available values for capture. The first one is user which defines the user-facing input and the other one is environment which defines the outward-facing input.

<label for="imageFile">Upload a photo of yourself:</label>
<input type="file" id="imageFile" capture="user" accept="image/*">

So, how does this work?

If the browser and device supports the capture attribute, once you interact with "Choose file..." instead of seeing your media folder, your camera will be activated, and you can take a picture straight away and submit it.

Video #

You could also use trigger the video input directly, by using:

<input type="file" id="videoFile" capture="user" accept="video/*">

It will work almost the same way as for images, except it will switch automatically to video in your camera app.

Audio #

In addition to image and video you can also directly trigger the build in audio recorder.

<input type="file" id="audioFile" capture="user" accept="audio/*">

Support #

At the moment (January 2021), this is only supported on mobile browsers (iOS Safari, Chrome for Android, Opera Mobile, Samsung Internet,...) and will not work on any desktop device. Browsers not supporting it will fall back to the default media picker.

I also found that on Android you will always get the outward-facing camera (for image and video) no matter if you use user or environment as the value. This is probably because capture was originally a Boolean, and it looks like they haven't updated their implementation. For audio, it doesn't matter (for now) as most devices only have one audio input.

Demo #

You can try it yourself in this JS Bin demo.

Resources #

Browser Support
MDN documentation