Styled file input
A Pen by Rico Sta. Cruz on CodePen.
<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; | |
} |