Design a captivating Profile Picture form using HTML and CSS styling

In my form, I am looking to include a user's Profile picture which should be displayed in either a circular or rectangular shape. Initially, the image area will show a black background or a placeholder image. When the user clicks on this area, they should be able to select an image just like how profile picture uploads work on social media platforms such as Facebook and Twitter.

https://i.stack.imgur.com/YQu5k.png

My Form HTML
<div class="signup-w3ls">
    <div class="signup-agile1">
        <form action="#" method="post">
        
            <div class="form-control">
                <label class="header">Profile Photo:</label>
                
                <input id="image" type="file" name="profile_photo" placeholder="Photo" required="" capture>
            </div>

            <!-- Other form inputs removed for brevity -->
            
            <input type="submit" class="register" value="Register">

        </form>
    </div>
</div>
CSS
.signup-w3ls {
    width: 50%;
    margin: 70px 25% 80%;
    padding: 0;
    display: table;
    position: relative;
}
/* CSS styling rules removed for brevity */

JSFIDDLE:- https://jsfiddle.net/7ao1qxLe/

Answer №1

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>

Answer №2

$("#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;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    -ms-border-radius: 50%;
    -o-border-radius: 50%;
    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>

Answer №3

Include a separate Image tag with the default image, then retrieve the URL when selecting an image using an input tag.

<img id="profile" src="default.png" alt="profile-image" />

function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            
            reader.onload = function (e) {
                $('#profile').attr('src', e.target.result);
            }
            
            reader.readAsDataURL(input.files[0]);
        }
    }
    
    $("#image").change(function(){
        readURL(this);
        //other uploading proccess [server side by ajax and form-data ]
    });

Fiddle Link: https://jsfiddle.net/7ao1qxLe/1/

Answer №4

To incorporate the picture selector, you can utilize the code snippet provided below

<img id="idcardfront" src="images/UploadImgPlaceholder.png" data-type="editable" />
<script>
$("#idcardfront").each(function (i, e) {
var _inputFile = $('<input/>')
.attr('type', 'file')
.attr('hidden', 'hidden')
.attr('id', 'idCardFrontFile')
.attr('onchange', 'readImage()')
.attr('data-image-placeholder', e.id)
.attr('Class', 'hidden');
 $(e.parentElement).append(_inputFile);
 $(e).on("click", _inputFile, triggerClick);
 });
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why isn't the alert box showing up when I use this Jquery function?

It has come to my attention that when I include the ready event, the function works properly. However, upon removing it, the function ceases to work. Functionality with Ready Event: <script type="text/javascript"> $(document).ready( functi ...

Assigning a variable within a parent function from a child function in JavaScript

Struggling to assign the value of "result" in the inner function. Any suggestions on how to do this? I am able to console log the result variable inside the function, but a friend recommended using promises. However, I have no clue how to implement that ...

CodePen displaying CSS errorsI'm having trouble getting my CSS

I'm facing an issue with my CSS code and I need your help to figure out what's wrong. I believe it's a simple problem that someone can quickly identify just by looking at the code. Any assistance would be greatly appreciated! Here is the co ...

What is the method to obtain the keycode for a key combination in JavaScript?

$(document).on('keydown', function(event) { performAction(event); event.preventDefault(); }); By using the code above, I am successful in capturing the keycode for a single key press. However, when attempting to use a combin ...

The action 'onDeleteClick' cannot be executed as the property is undefined

Why is the onDeleteClick function working on the first <div>, but returning undefined on the second one? I am able to access the reference of this, but when clicking, it shows "onDeleteClick of undefined". I am confused as to why the onDeleteClick f ...

Why is React's nested routing failing to render properly?

click here for image portrayal I am currently attempting to integrate react router, specifically a nested router. However, when I click the links on the contact page, no results are being displayed. Any assistance would be greatly appreciated. For more in ...

Can you identify any issues with this Javascript code's "If" condition?

In my JavaScript code, I have an "if condition" that looks like this: for (var i in data) { //Gender.push("Gender " + data[i].JenisKelaminID); if (data[i].JenisKelaminID == 1) { Gender.push("Men"); } if (data[i].JenisKelaminID == 2) { Gend ...

What order do Node.js event queues, Promises, and setTimeout() operate in?

QUERY: When working with Node.js event queues, such as code like "new Promise((r) => setTimeout(r, t));", where exactly is the setTimeout() function evaluated? Is it immediate, in the microqueue for Promise resolutions, or elsewhere? INSIGHT ...

Display a div based on user selection using Ajax and Laravel

There are two div elements on the index page containing a datatable. By default, these two divs should be hidden. When an option is selected from the dropdown menu, the corresponding div should be displayed. The webpage is designed for searching within a ...

Retrieve data from an external website containing an HTML table without a table ID using Java Script and transform it into JSON

I have developed a script that can convert HTML table data into a JSON Object. To accomplish this task, I utilized the jquery plugin created by lightswitch05. With this code, I am able to extract data from an HTML table on the same web page using: var t ...

Merge two JSON files into a single document

I am currently working on a script that is able to access a JSON file by using the code: $.getJSON( 'alfred.json', function(data) { ... } Recently, I have obtained a second file named alfred_offline.json, which follows the same structure a ...

Is there a way to eliminate the gap beneath each row of my Tic-Tac-Toe grid in Next.js with CSS styling?

What could be causing the space under every row in my CSS? I am currently developing a tic-tac-toe application using Next.js to enhance my skills. However, I have encountered an issue with the CSS where there appears to be a small space underneath each bo ...

What is the best way to include an "average" line in a nvd3.js Stacked Area Chart?

My Stacked Area Chart is up and running smoothly using NVD3.js. You can view it in action on this working jsfiddle link. var volumeData = [{"key":"Hit","values":[[1.3781628E12,12],[1.3782492E12,9],[1.3783356E12,9],[1.378422E12,4],[1.3785084E12,2],[1.37859 ...

Maintaining checked items in their original state while searching for another one in ion-searchbar can be achieved by properly handling

My goal is to maintain the checked items as checked when searching for another item in ion-searchbar. While I have managed to keep the checked items, the checkmark icon does not stay checked. What I aim for is to retain the checked state of all food items ...

This is my first experience with Flask and I am encountering an issue with the POST method

Recently, I began my journey of learning Flask and encountered a seemingly simple task: creating a button, capturing the name, and displaying it on the screen. Despite my efforts, the code doesn't seem to be working as expected. It's now been two ...

The custom server was functioning properly, but as soon as I altered the file directory, an error occurred on Next.js

After creating "create-next-app," I successfully set up the folder structure as follows: +client2 --.next --node_modules --public --... --server.js However, when I move my "server.js" file to a different location: +client2 --.next --no ...

Failed to validate user profile because of an InternalOAuthError error while using passport-facebook-token to verify the token

In my iOS application, I am utilizing the Facebook API for user login and receiving an access token in return. Now, I need to use this token to verify a user on my backend server. For this purpose, I have implemented the passport-facebook-token strategy w ...

Exploring the Power of Ajax in Struts2

Recently, I started learning about Struts and Ajax. I attempted to create a webpage similar to Gmail, where users enter their username first and then proceed to enter their password. Despite trying out various plugins like Dojo, jQuery, and Jason jars, I ...

Spin the object at regular intervals

Recently, I stumbled upon this interactive Pen: https://codepen.io/golle404/pen/BoqrEN that caught my eye. I thought it would be interesting to make the object move every few seconds. My first attempt involved using the following code snippet: setTimeout( ...

Polyfill for window.showOpenFilePicker function

Could anyone recommend a polyfill for the window.showOpenFilePicker method? For reference, you can check out the documentation on MDN. ...