Skip to content

Instantly share code, notes, and snippets.

@CodeMyUI
Created April 20, 2018 01:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CodeMyUI/82bee50b97e0e96d5ea1296ca6703772 to your computer and use it in GitHub Desktop.
Save CodeMyUI/82bee50b97e0e96d5ea1296ca6703772 to your computer and use it in GitHub Desktop.
Styled file input
<div class='file-input'>
<input type='file'>
<span class='button'>Choose</span>
<span class='label' data-js-label>No file selected</label>
</div>
// Also see: https://www.quirksmode.org/dom/inputfile.html
var inputs = document.querySelectorAll('.file-input')
for (var i = 0, len = inputs.length; i < len; i++) {
customInput(inputs[i])
}
function customInput (el) {
const fileInput = el.querySelector('[type="file"]')
const label = el.querySelector('[data-js-label]')
fileInput.onchange =
fileInput.onmouseout = function () {
if (!fileInput.value) return
var value = fileInput.value.replace(/^.*[\\\/]/, '')
el.className += ' -chosen'
label.innerText = value
}
}
* {
box-sizing: border-box;
}
body {
padding: 42vh 32px;
font-size: 14px;
background: #eee;
text-align: center;
}
.file-input {
display: inline-block;
text-align: left;
background: #fff;
padding: 16px;
width: 450px;
position: relative;
border-radius: 3px;
}
.file-input > [type='file'] {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
z-index: 10;
cursor: pointer;
}
.file-input > .button {
display: inline-block;
cursor: pointer;
background: #eee;
padding: 8px 16px;
border-radius: 2px;
margin-right: 8px;
}
.file-input:hover > .button {
background: dodgerblue;
color: white;
}
.file-input > .label {
color: #333;
white-space: nowrap;
opacity: .3;
}
.file-input.-chosen > .label {
opacity: 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment