DEV Community

Mr Shanas
Mr Shanas

Posted on • Originally published at mrshanas.com on

Custom File Uploader

Hello there it's 2023 and are you bored of the default tedious file input that HTML offers?, well I want to share how you can create a custom file input using HTML with little TS 😅 oh sorry!! had you there, I meant js .

Firstly generate a plain HTML project and paste the code below

<input type="file" name="" id="file-input" hidden />

    <div
      class=""
      style="
        width: 200px;
        height: 200px;
        border: 1px dashed #aaa;
        margin: 0 auto;
        display: grid;
        place-items: center;
        cursor: pointer;
      "
    >
      <p style="color: #00f">Click here to upload</p>
    </div>

Enter fullscreen mode Exit fullscreen mode

The HTML code above contains two tags, the input tag is hidden because we don't want that but we'll use its functionality. The code will roughly be displayed as shown below(Don't mind my CSS 😅)

Now for the fun part let's see some js

     const fileInput = document.getElementById("file-input");
     const div = document.querySelector("div");

    div.addEventListener("click", () => {
      fileInput.click();
    });

Enter fullscreen mode Exit fullscreen mode

The code above retrieves the input and div elements using their id's and assigns an event listener to the div element that when clicked it triggers the click event on the file input that allows your users to select any file for uploading, from here you can choose to do anything with the image.

Top comments (0)