Show Video Preview using JavaScript is a useful feature when you want users to see their selected video before uploading it to the server. Social media platforms like Facebook and Twitter use this functionality to help users confirm their video choice.
You can easily implement similar functionality with JavaScript. In this article, we will provide a simple example where a user selects a video file, and the script displays a preview of the selected video.
Video preview will reduce server load and same time user can check video file is valid or not. Here we will use the URL.createObjectURL() method to show a preview.
First of all, let’s define basic markup for our web page then we will add our JavaScript code for showing a preview. create a new file or you can use your existing markup for it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Video Preview Using JavaScript</title>
</head>
<body>
<input id="video" type="file" name="file">
<video width="320" height="240" controls>
Your browser does not support the video tag.
</video>
</body>
</html>Here, we just added a simple input field with the file type and assign id to it. Also defined HTML video element with height and width attributes.
Now we will add a trigger to show a preview. Whenever the event triggers, we set the video tag src as blobURL, which is the URL.createObjectURL of the selected video file. The browser will automatically show a preview of the video element and add basic control as per our attributes.
Further, we will add below JavaScript code at the end of the body tag.
document.getElementById("video").onchange = function(event) {
let file = event.target.files[0];
let blobURL = URL.createObjectURL(file);
document.querySelector("video").src = blobURL;
}The above code will get the selected file and create a URL from the file. Then we will set the video tag’s src attribute with that URL which will show the video preview to the user.
Conclusion
In this article, we have taken a simple example showing a video preview to the user using JavaScript-based logic. There are many ready to use a library to perform this task easily. But those packages contain logic similar to this.
When letting users upload files, giving them a visual preview can improve the experience. A good example is showing how to preview images with jQuery before the actual upload.

