In HTML, we have several types of input elements and one of them is of type file. When we create an input element and click on it, we get a popup window asking to choose a file from our system.

Sometimes, especially when implementing our UI, we may want to open the window to select a file on the click of a button. Developers earlier used to depend on libraries such as jQuery to implement it,but doing it with Vanilla JavaScript without depending on any external library is also very easy.

All you need to do is, create an input element, and make it not visible. When the user clicks on a button, trigger click event on the input element.

example code:


<!DOCTYPE html>
<html lang="en">

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="" rel="stylesheet"
        integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <link rel="stylesheet" href="styles.css">


<body class="container">
    <input type="file" name="" id="fileInput" style="display: none;">
    <button class="btn btn-primary" id="fileButton">Select a File</button>

    <script src="index.js"></script>



let fileButton = document.getElementById('fileButton');
let fileInput = document.getElementById('fileInput');

fileButton.addEventListener('click', () => {