Explain Codes LogoExplain Codes Logo

Change default text in input type="file"?

html
responsive-design
css
javascript
Alex KataevbyAlex Kataev·Dec 25, 2024
TLDR

To replace the default text in input[type="file"], hide the original input with CSS, then add a custom button that triggers the file selection. Here's a simplified version:

<style> #file-upload { display: none; // Hide and Seek champion 2022 } </style> <input type="file" id="file-upload"/> <button onclick="document.getElementById('file-upload').click()">Upload File</button>

This hides the original file input tag using CSS, a button element is then styled as you see fit. The onclick event on the button fires the hidden file input.

A practical guide to customizing file inputs

Step 1: The label-force awakens

To start, pair a label with the input using the for attribute. This ensures accessibility:

<label for="file-upload" class="custom-file-upload"> Click me, or not. You're the boss! </label> <input type="file" id="file-upload" style="visibility:hidden;"/>

Step 2: Becoming a CSS Wizard

Apply CSS magic to transform the label into a button:

.custom-file-upload { display: inline-block; padding: 6px 12px; background-color: #f0f0f0; border: 1px solid #ccc; border-radius: 4px; cursor: pointer; // Pointy thing changes here. Spooky! }

Step 3: Power up with JavaScript

Fetch and display the originally uploaded file name with JavaScript to provide users with instant feedback:

document.getElementById('file-upload').onchange = function(e) { document.querySelector('.custom-file-upload').innerText = e.target.files[0].name || 'Click me!'; };

Step 4: Frameworks are friends, not foes

Bootstrap or Ratchet can help maintain consistent styling across different browsers and devices.

Minding the bits and pieces

Keep it user-friendly

Always mimic native input behavior to maintain user familiarity with the interaction.

Adapt to different screen sizes

Make sure your customized button looks good and performs well on all devices.

Display selected files

Use event listeners to capture uploaded file names and display them to users.

Blend with overall design

Matching the custom button with your application's design language ensures a seamless user experience.