jQuery Image Uploader

by MD Hasan Patwary

HTML

<div class="image-uploader">
  <input type="file" id="file-input" accept="image/*">
  <div class="image-preview" id="image-preview">
    <img id="image-preview-img" src="placeholder.jpg" alt="Preview" />
    <div class="edit-icon">✏️</div>
  </div>
</div>

CSS

body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
    font-family: Arial, sans-serif;
}

.image-uploader {
    position: relative;
    width: 200px;
    height: 200px;
    border: 2px dashed #ccc;
    border-radius: 10px;
    overflow: hidden;
    cursor: pointer;
}

#file-input {
    position: absolute;
    width: 100%;
    height: 100%;
    opacity: 0;
    cursor: pointer;
}

.image-preview {
    position: relative;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f0f0f0;
}

.image-preview img {
    max-width: 100%;
    max-height: 100%;
}

.edit-icon {
    position: absolute;
    bottom: 10px;
    right: 10px;
    display: none;
    background-color: rgba(0, 0, 0, 0.5);
    color: white;
    border-radius: 50%;
    padding: 5px;
    cursor: pointer;
}

JavaScript

$(document).ready(function() {
    $('#file-input').on('change', function(event) {
        const file = event.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                $('#image-preview-img').attr('src', e.target.result).show();
                $('.edit-icon').show();
            }
            reader.readAsDataURL(file);
        }
    });

    $('.image-uploader').on('click', function() {
        $('#file-input').click();
    });
});