About this snippet

Allow users to preview their avatar before uploading it. This snippet handles the file selection event and instantly updates the image source, which provides immediate visual confirmation.

Size
1.5 KB
Uses
HTML, CSS, JavaScript
Loads
placehold.co
Views
533
<div class="profile-upload">
  <div class="image-container">
    <img src="https://placehold.co/150x150/e5e7eb/a3a3a3?text=No+Image" id="previewImg" alt="Profile">
    <label for="fileInput" class="edit-btn">&#9998;</label>
  </div>
  <input type="file" id="fileInput" accept="image/*" hidden>
  <p>Click the pencil to upload</p>
</div>
.profile-upload {
  font-family: system-ui, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
  text-align: center;
}
.image-container {
  position: relative;
  width: 150px;
  height: 150px;
  margin: 0 auto 15px;
}
#previewImg {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  border: 4px solid #fff;
  box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}
.edit-btn {
  position: absolute;
  bottom: 5px;
  right: -10px;
  background: #3b82f6;
  color: white;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border: 3px solid #fff;
  transition: background 0.2s;
}
.edit-btn:hover {
  background: #1d4ed8;
}
p {
  color: #6b7280;
  font-size: 0.9rem;
}
const fileInput = document.getElementById("fileInput");
const previewImg = document.getElementById("previewImg");

fileInput.addEventListener("change", function(event) {
  const file = event.target.files[0];
  if (file) {
    const reader = new FileReader();
    reader.onload = function(e) {
      previewImg.src = e.target.result;
    };
    reader.readAsDataURL(file);
  }
});
Esc
↑↓ moveEnter select

Start from a template

Open an .html file, or HTML, CSS, JS, Markdown, Less or TypeScript files. You can also drop them here. Styles and scripts go into their panes.

Share

Source

Keyboard shortcuts

Save