To add an image, simply click on the designated area instead of using the traditional file input button. The image will then be displayed in the specified image container and resized on the client-side

Objective:

I am aiming to enhance the image upload functionality by enabling users to click on an <img> element to initiate the file selection process, instead of using the traditional <input type="file"> button. There will be three placeholders initially displayed on the page, and upon clicking on any placeholder, the user can choose a file which will then be displayed in the respective placeholder. Below is what I have implemented so far:

HTML:

<div class="image-upload">
   <label for="file_input1">
       <img id="send_photo_img1" src="assets/images/index2.png"/&>
   </label>
   <input id="file_input1" type="file"/>
</div>  

CSS:

.image-upload > input
{
    display: none;
}

.image-upload img
{
    display: inline-block;
    margin-right:6px;
    width: 90px;
    height: 90px;
    cursor: pointer;
}

Jquery:

function readURL(input) {

if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function (e) {
        $('#send_photo_img1')
            .attr('src', e.target.result);
    }

    reader.readAsDataURL(input.files[0]);
}
}    

$("#send_photo_img1").change(function(){
    readURL("#file_input1");
});

While libraries like plupload.js or dropzone.js offer similar functionalities, they come with additional features that are unnecessary for my current project requirements. Therefore, I am customizing the implementation to fit precisely what I need.

The existing code allows me to select an image, but it fails to display it. Currently, after selecting an image, a loading icon appears briefly, but no further action takes place. Additionally, there are no error messages displayed in the Chrome DevTools console.

Answer №1

Discovered the solution, and it turned out to be quite simple:

HTML

<div class="img_upload">
    <img class="send_photo_img" id="send_photo1_img" src="assets/images/index2.png"/>
    <input id="send_photo1" name="send_photo1" class="send_photo_input" type="file"/>
</div>
<div class="img_upload">
    <img class="send_photo_img" id="send_photo2_img" src="assets/images/index2.png"/>
    <input name="send_photo2" class="send_photo_input" type="file"/>
</div>  

You can have as many images as you want.

Next, using CSS, hide the <input> element and trigger its click event through JavaScript when the associated <image> is clicked:

CSS

.img_upload input
{
    display: none;
}

JS (to trigger the click)

$(".img_upload img").click(function(){
        img = $(this);
        input = img.next(".send_photo_input");
        var newUrl;

        input.trigger("click");
        input.change(function(){
            newUrl = resize_and_draw(this, img.width());
            url.push(newUrl);
    });
});

Lastly, utilize HTML5 canvas for further processing (almost universally supported except by Opera Mini).

If you're interested in client-side image resizing for bandwidth and load speed considerations, here is the full code:

function resize_and_draw (input, targetH) {

if (input.files && input.files[0] && /\.(jpe?g|png|gif)$/i.test(input.files[0].name)) {

    var reader = new FileReader();
    reader.onload = function (e) {

        var img = new Image();
        img.src = reader.result;
        img.onload = function() {

          canvas = document.createElement( 'canvas');
            canvas.width = img.naturalWidth;   
            canvas.height = img.naturalHeight;
            context = canvas.getContext('2d');
            context.drawImage( img, 0, 0, img.naturalWidth, img.naturalHeight );

                targetHeight = targetH;
            targetWidth = img.naturalWidth * targetHeight / img.naturalHeight;

            //resize
            resample_hermite(canvas, img.naturalWidth, img.naturalHeight, targetWidth*2, targetHeight*2);
            url = canvas.toDataURL("image/png");
            $(input).prev(".send_photo_img").attr('src', url);

        }     
    }

    reader.readAsDataURL(input.files[0]);

    return url;
}
}

Hope this guide aids your endeavors. Cheers!

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

The test() function in JavaScript alters the output value

I created a simple form validation, and I encountered an issue where the test() method returns true when called initially and false upon subsequent calls without changing the input value. This pattern repeats with alternating true and false results. The H ...

How to maintain the focus within a jQuery dialog box

Exploring the world of jQuery dialog, I'm eager to incorporate it into my latest side project. My goal is to enhance accessibility by adding tabindex to the divs within the dialog for easy tab navigation. However, I encountered an issue where the focu ...

Obtaining data using Classic ASP from an ajax JSON post can be achieved by following these

I am currently working on sending data to classic asp using ajax json. The json successfully calls the asp page, but there is an issue with the data not reaching the backend. As a result, the database is unable to be modified based on the new sort order. ...

How can the table header be displayed in a Vue JS application after receiving the server response?

On my Vue.JS web page, I am making an API call using the Http GET method. Currently, the table header is displayed before receiving the API response, which doesn't look good. Can someone help me modify my code so that the table header is only displaye ...

Guide to adding a line break following each set of 200 characters utilizing jQuery

I have a text input field where I need to enter some data. My requirement is to automatically add a line break after every 200 characters using JavaScript or jQuery. For example: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ...

Using the ternary operator in various CSS rules

Inside a .hover() function, I've written the code below: $(this).css('background-position', circle.includesXY(e.pageX, e.pageY) ? 'bottom' : ''); I'm wondering how to include additional property:value pairs within ...

The right column in a relatively positioned layout descends as an element in the left column is revealed

Currently in the process of constructing a registration form for our website, everything is going smoothly with one minor hiccup. The form consists of two columns where users enter their information. Initially, when designing elements for the first (left) ...

Expanding the `div` element to visually occupy the entire vertical space

I'm facing a design challenge with my webpage layout. I have a fixed header and footer, but I need the content section to dynamically adjust its height between the two. The goal is to fill the remaining vertical space with a background-image in the co ...

Having trouble getting the .toggle() function with classList to work on one element, despite working fine on others

I've been struggling to apply a class to an HTML element when I click on another element of the page. Despite numerous attempts, it just doesn't seem to work for me. Let's take a look at my code: HTML Code: <div class="container&qu ...

Dynamic row additions causing vanishing rows in the table due to JS/jQuery implementation

I am currently facing an issue while trying to create a table where I can add rows dynamically. Despite looking at various solutions on this topic, none of them seem to resolve the problem I am encountering. The newly added rows disappear immediately after ...

Ways to insert user data into a hidden input field

I am facing an issue with the input field on my website. Users can enter their desired input, and this data is copied into a hidden input field. However, the problem arises when new data replaces the old data. This is where I copy all the data: $('# ...

Can you generate a new element based on a template element?

I'm encountering an issue with the following code snippet: template = $("#template"); $(template).attr("id", "newid"); $(template).appendTo("body"); My goal is to assign an id to the template and then modify its content. However, I seem to be direc ...

Tips for creating a clickable A href link in the menu bar that triggers an accordion to open in the body when clicked - html

Is there a way to open the first accordion when clicking on the "open 1st accordion" link, and do the same for the second link? The accordions themselves work perfectly fine, I just need a way to trigger them from outside their scope by clicking on links i ...

Optimizing web layouts to fit on a single page is the most effective

Struggling to create a print layout for my web page that seamlessly transitions from the digital realm to the physical world. Utilizing HTML and CSS has presented challenges in aligning the "digital" design with a "real printable" page due to uncertainties ...

Is there a way to ensure that when displaying information boxes with Bootstrap, the inputs do not get misplaced or shuffled to the wrong location

I have been working on a form that needs to display an alert: When clicking the button next to the input control, an alert should appear. Although the alert is showing correctly, the input controls are shifting to the wrong position afterwards: The desir ...

Troubleshooting a problem with CSS Matrix animations

Lately, I've been working on creating some matrix animations. However, I noticed an unusual issue. The code below seems to function differently across Firefox, Safari, and Chrome: @-moz-keyframes matrix { from { -moz-transform: matri ...

Tips for concealing the URL in the address bar while using `<a href>` links

I have a variety of documents saved in a folder within an ASP MVC 5 project. Instead of directly linking to the document with an HTML tag, I am utilizing the following ng-href: <a ng-href="~/download/document/{{vm.document}}"></a> By using th ...

Is HTML5 data-target used for loading pages?

Currently, I am working with some HTML5 code: <li class="tile google" data-target-activation="click" data-target="loading"> <div> <a href="#">Search Google</a> <h2>Google</h2> </div> </li> Upon ...

Showing information from the data text option

I'm having trouble displaying text below the cube. The code works fine in a standalone fiddle, but it doesn't work when I incorporate it into my project. Can someone help me figure out how to show the value of data-text="Cube1"? Code t ...

How can I detect the scroll action on a Select2 dropdown?

Is there a way to capture the scrolling event for an HTML element that is using Select2? I need to be able to dynamically add options to my dropdown when it scrolls. Just so you know: I am using jQuery, and the dropdown is implemented with Select2. The ...