Upload user avatar with a custom upload button

bugs_bunny

Derek Oware

Posted on October 7, 2020

Upload user avatar with a custom upload button

I recently wrote on how to customize the default upload button but I want to explore more into this topic and try other options.

I designed an interface to upload a user avatar

final look

How to

We'll start with our HTML

<main>
  <input type="file" name="image" id="image" accept="image/*" />
    <div id="preview-wrapper">
      <div id="preview"></div>
      <button
        id="upload-button"
        aria-label="upload image"
        aria-describedby="image"
      >
        🙂
      </button>
    </div>
</main>
Enter fullscreen mode Exit fullscreen mode

Styling

We give some style for our user avatar.

#avatar {
  background-color: antiquewhite;
  height: 200px;
  width: 200px;
  border: 3px solid #0af;
  border-radius: 50%;
  transition: background ease-out 200ms;
}

#preview {
  position: relative;
}
Enter fullscreen mode Exit fullscreen mode

We then hide our input

input[type="file"] {
  display: none;
}
Enter fullscreen mode Exit fullscreen mode

Then our custom upload button

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;
}

Enter fullscreen mode Exit fullscreen mode

We've reached our design goal 🙌, but we aren't done yet.

Some JavaScript

Our initialization

const UPLOAD_BUTTON = document.getElementById("upload-button");
const FILE_INPUT = document.querySelector("input[type=file]");
const AVATAR = document.getElementById("avatar");
Enter fullscreen mode Exit fullscreen mode

When our custom button is clicked, we have to programmatically click the input element

UPLOAD_BUTTON.addEventListener("click", () => FILE_INPUT.click());
Enter fullscreen mode Exit fullscreen mode

To render our image

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`;
  };
});
Enter fullscreen mode Exit fullscreen mode

WE ARE DONE!!! 🥳🥳🥳

Source code available at codepen.io and github

💖 💪 🙅 🚩
bugs_bunny
Derek Oware

Posted on October 7, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related