Upload user avatar with a custom upload button
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
<main> | |
<input type="file" name="image" id="image" accept="image/*" /> | |
<div id="preview"> | |
<div id="avatar"></div> | |
<button | |
id="upload-button" | |
aria-labelledby="image" | |
aria-describedby="image" | |
> | |
🙂 | |
</button> | |
</div> | |
</main> |
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
const UPLOAD_BUTTON = document.getElementById("upload-button"); | |
const FILE_INPUT = document.querySelector("input[type=file]"); | |
const AVATAR = document.getElementById("avatar"); | |
UPLOAD_BUTTON.addEventListener("click", () => FILE_INPUT.click()); | |
FILE_INPUT.addEventListener("change", event => { | |
const file = event.target.files[0]; | |
const reader = new FileReader(); | |
reader.readAsDataURL(file); | |
reader.onloadend = () => { | |
AVATAR.setAttribute("aria-label", file.name); | |
AVATAR.style.background = `url(${reader.result}) center center/cover`; | |
}; | |
}); |
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
body { | |
display: flex; | |
justify-content: center; | |
align-items: center; | |
height: 100vh; | |
} | |
#avatar { | |
background-color: antiquewhite; | |
height: 200px; | |
width: 200px; | |
border: 3px solid #0af; | |
border-radius: 50%; | |
transition: background ease-out 200ms; | |
} | |
#preview { | |
position: relative; | |
} | |
input[type="file"] { | |
display: none; | |
} | |
button { | |
padding: 18px; | |
border-radius: 50%; | |
border: none; | |
cursor: pointer; | |
background-color: #08f; | |
box-shadow: 0px 3px 5px -1px rgba(0, 0, 0, 0.2), | |
0px 6px 10px 0px rgba(0, 0, 0, 0.14), 0px 1px 18px 0px rgba(0, 0, 0, 0.12); | |
transition: background-color ease-out 120ms; | |
position: absolute; | |
right: -5%; | |
bottom: 0%; | |
} | |
button:hover { | |
background-color: #45a; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment