If you want to make the input hidden and simulate a click when the profile image is clicked, you can achieve it like this:
$("#profileImage").click(function(e) {
$("#imageUpload").click();
});
#imageUpload
{
display: none;
}
#profileImage
{
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<image id="profileImage" src="http://lorempixel.com/100/100" />
<input id="imageUpload" type="file"
name="profile_photo" placeholder="Photo" required="" capture>
Previewing the Image
You can also provide the user with a preview of the uploaded image using JavaScript:
function showImagePreview( uploader ) {
//check if a file has been chosen
if (uploader.files && uploader.files[0]) {
var imageFile = uploader.files[0];
var reader = new FileReader();
reader.onload = function (e) {
//set the source of the image data
$('#profileImage').attr('src', e.target.result);
}
reader.readAsDataURL( imageFile );
}
}
$("#imageUpload").change(function(){
showImagePreview( this );
});
Tip for efficiency: You can use createObjectURL
instead of reading data as URL for better performance.
function fasterPreview( uploader ) {
if ( uploader.files && uploader.files[0] ){
$('#profileImage').attr('src', window.URL.createObjectURL(uploader.files[0]));
}
}
Check out more about MDN's createObjectURL, where it generates the file URL without loading it into the DOM.
Circular Image Cropping
To display the image in a circular crop, wrap it in an outer div
and apply a border-radius
:
HTML:
<div id="profile-container">
<image id="profileImage" src="defaultImage.png" />
</div>
CSS:
#profile-container {
width: 150px;
height: 150px;
overflow: hidden;
border-radius: 50%;
}
Complete Code Solution
This code combines all the steps mentioned above:
$("#profileImage").click(function(e) {
$("#imageUpload").click();
});
function fasterPreview( uploader ) {
if ( uploader.files && uploader.files[0] ){
$('#profileImage').attr('src', window.URL.createObjectURL(uploader.files[0]));
}
}
$("#imageUpload").change(function(){
fasterPreview( this );
});
#imageUpload
{
display: none;
}
#profileImage
{
cursor: pointer;
}
#profile-container {
width: 150px;
height: 150px;
overflow: hidden;
border-radius: 50%;
}
#profile-container img {
width: 150px;
height: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="profile-container">
<image id="profileImage" src="http://lorempixel.com/100/100" />
</div>
<input id="imageUpload" type="file"
name="profile_photo" placeholder="Photo" required="" capture>