A Pen by Rico Sta. Cruz on CodePen.
Created
April 20, 2018 01:55
-
-
Save CodeMyUI/82bee50b97e0e96d5ea1296ca6703772 to your computer and use it in GitHub Desktop.
Styled file input
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class='file-input'> | |
<input type='file'> | |
<span class='button'>Choose</span> | |
<span class='label' data-js-label>No file selected</label> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
* { | |
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