JSFiddle - React, Tailwind, and code Playground
by thanhansoft
HTML
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<div class="hero">
<label class="drop-area">
<input type="file" accept="image/*" class="input-file" hidden>
<div class="img-view">
<img src="icon.png">
<p>Drag and drop or click here<br>to upload image</p>
<span>Upload any images from desktop</span>
</div>
</label>
</div>
<div class="hero">
<label class="drop-area">
<input type="file" accept="image/*" class="input-file" hidden>
<div class="img-view">
<img src="icon.png">
<p>Drag and drop or click here<br>to upload image</p>
<span>Upload any images from desktop</span>
</div>
</label>
</div>
CSS
.hero {
display: flex;
align-content: center;
justify-content: center;
flex-direction: column;
margin-bottom: 20px;
}
.drop-area {
width: 500px;
height: 300px;
padding: 30px;
background: #fff;
text-align: center;
border-radius: 20px;
}
.img-view {
width: 100%;
height: 100%;
border-radius: 20px;
border: 2px dashed #bbb5ff;
background: #f7f8ff;
background-position: center;
background-size: cover;
}
.img-view img {
width: 100px;
margin-top: 25px;
}
.img-view span {
display: block;
font-size: 12px;
color: #777;
margin-top: 15px;
}
JavaScript
$('.input-file').each(function() {
const inputFile = $(this);
const dropArea = inputFile.closest('.drop-area');
const imageView = dropArea.find('.img-view');
inputFile.on('change', function() {
uploadImage(inputFile, imageView);
});
dropArea.on('dragover', function(e) {
e.preventDefault();
dropArea.addClass('dragover');
});
dropArea.on('dragleave', function(e) {
e.preventDefault();
dropArea.removeClass('dragover');
});
dropArea.on('drop', function(e) {
e.preventDefault();
dropArea.removeClass('dragover');
inputFile[0].files = e.originalEvent.dataTransfer.files;
uploadImage(inputFile, imageView);
});
dropArea.on('click', function() {
inputFile.click();
});
});
function uploadImage(inputFile, imageView) {
let imgLink = URL.createObjectURL(inputFile[0].files[0]);
imageView.css('background-image', `url(${imgLink})`);
imageView.find('img, p, span').hide();
imageView.css('border', '0');
}