I am currently designing a form using HTML, CSS, and JavaScript which includes an input type=file. I customized the form, so that the input now uses an image which can be clicked to browse and select files from the user’s machine. However, I’d also like it to have drag & drop capabilities.
Below is the code I currently have. This code is enough to do a couple of things:
- It replaces the default ‘Choose File’ button that is rendered when using the input tag with type=file with the image called in the img tag.
- It uses some JavaScript for the span tag to indicate to the user which file they have selected or if no file has been selected.
The reason those are possible is because of the CSS used to change the default behavior in the input tag where type=file. However, I haven’t found code to implement drag & drop to my current solution. Can somebody please help?
<style>
.required-file::after {
content: "*";
color: red;
}
.custom-upload {
display: inline-block;
padding: 6px 12px;
cursor: pointer;
}
input[type="file"] {
display: none;
}
</style>
<script>
$(function() {
const fileUploadElement = document.getElementById('fileUpload');
const chosenFileElement = document.getElementById('chosen-file');
fileUploadElement.addEventListener('change', function(){
chosenFileElement.textContent = this.files[0].name;
});
});
</script>
<label for="fileUpload" class="custom-upload">
<img src="/fakepath/image.png" width="100" height="100">
</label>
<input type="file" id="fileUpload" name="fileUpload" >
<span class="required-file" id="chosen-file">No file chosen</span>
2
Answers
Based on your requirements to add drag-and-drop capabilities and display the selected image, I’ve modified your code to include these features. Below is the updated HTML, CSS, and JavaScript that supports both functionalities seamlessly. This setup allows users to either click on the custom upload area to select a file or drag and drop a file onto it, and then immediately preview the selected image.
what you are trying to do can easily be achieved with the javascript plugin called Dropzone and you can read more about the available configuration for the plugin dropzone configuration.
Below is an example: