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

Transfering data to Handlebars while rendering a template

Is there a method to pass a variable to a handlebars template during its rendering process? Below is the template in question: <script id="listingTopics" type="text/x-handlebars-template"> {{#each this}} <div class="wrapper_individual_listing ...

The jQuery target is not able to locate the specified element

Why does this code snippet work in one case: jQuery(this).closest("li").find("p").text(); But when enclosed within a function, it fails to produce the desired result: jQuery.each(words, function(i, v) { jQuery(this).closest("li").find("p").text(); } ...

What are your thoughts on using inline PHP to assign values to JavaScript variables?

Imagine you have a PHP document and need to determine if the request was made with or without query parameters using JavaScript. Since there is no built-in function to extract values from the URL, you may need to resort to some sort of workaround. While it ...

Enhancing jQuery UI Tabs with HoverIntent

I'm currently working on incorporating HoverIntent into my jQuery tabs, but I seem to be facing some issues. Below is the code snippet that I've been using. Any suggestions or tips would be greatly appreciated. Thank you! The code was sourced di ...

Trouble with the $.inArray function

Encountering an issue with storing objects into an array. However, when attempting to verify the existence of an object using $.inArray, it consistently returns -1. The code is written in AngularJS. <input name="{{question.number}}" ng-clic ...

Checking multiple IDs with jQuery to remove a specific class name

What I am trying to achieve is selecting a specific link by adding a class of "selected" when clicked. Here is the code snippet for that: $("#" + filename).addClass("selected"); In addition, I have another button that triggers a different function and it ...

When I set my header as "fixed", it automatically adjusts the size of the header box

Looking to create a fixed-header that includes clickable links on the left and our logo on the right. Encountering an issue when trying to make the header take up the full width of the screen in its fixed position. The header's width seems to shrink ...

Combine jQuery and CSS to create a scrollable and extended fixed header

I am experiencing an issue where the header is fixed when scrolled down, but when I scroll back up to the top, it detaches and becomes unfixed again. How can I make the header stay fixed for a prolonged period of time? Are there any specific adjustments I ...

Each time I perform an INSERT operation, I momentarily lose the structure property of my datatable

gif image for reference https://i.sstatic.net/MiWL4.gif I encountered an issue when adding a new record to the data table. I have included a gif image for better understanding. Below is my display function: function display_record() { table = $(&apo ...

Create dropdown options from JSON data

I'm attempting to populate a dropdown menu using a JSON response retrieved from an API. let dropdown = $('#LA_picker'); dropdown.empty(); dropdown.append('<option selected="true" disabled>Choose State/Province</option>& ...

The lack of an error event being triggered by jQuery when an ajax call fails has puzzled many users

Why doesn't jQuery trigger an error event when running the following script? Even though I've set up the error event, it's not being called. In Chrome's Network tab in the Console, I see this error: GET http://www.google.com/adfdaf?c ...

Implement the CSS display flex property for more flexible layouts

After working on some HTML code, I found the following: <section class = "personal_proyects"> <article> <div class = "personal_details"> <h3>Canal YT: Codigo RM</h3> < ...

HTML Elements for Displaying Undefined JSON Information

Hey there, I'm new to programming and I'm looking to display JSON data in an HTML table using jQuery. The issue I'm facing is that the output from the server shows up as 'undefined'. My goal is to have a constantly updated list of ...

The nested div escapes from its parent div despite the application of clearfix and the correct positioning of relative and absolute elements

Hey there, I have a question about using relative and absolute positioning along with applying clearfix to the main container in my code. The layout is quite simple - a nav-bar with a drop-down menu at the top, followed by a hero image spanning the screen, ...

Error message on WordPress or NPM: the JavaScript file for Bootstrap cannot run without jQuery loaded first

Currently, I am using NPM to bundle bootstrap along with several other scripts for a Wordpress theme. Since WordPress already loads jquery by default, I have made sure to exclude jquery from the bundle. However, even though I can see in Google Dev Tools t ...

Utilizing Vue Js and Query to retrieve data from a Jira Rest API endpoint

Trying to utilize the JIRA REST API within a Vue.js application has presented some challenges. After generating the API key, I successfully ran an API request using Postman. Initially, I attempted to use the axios client, but encountered issues with cross ...

Using Javascript, load a URL by making a JQuery ajax GET request and specifying custom headers

I currently have a small single-page application (SPA) using JQuery/Ajax for the frontend and Node/Express for the backend. The user authentication and authorization are handled with JSON-Webtoken, but I encountered an issue. If someone tries to access the ...

JQGrid will automatically conceal any row that contains a false value in a given cell

I'm attempting to conceal a row if a specific cell within it contains the value false. To achieve this, I have experimented with using a formatter in the following manner: $("#list").jqGrid({ //datatype: 'clientSide', ...

Is it possible for jQuery to eliminate script tags that are delivered through AJAX requests?

Upon making an AJAX request in my JavaScript code using jQuery, I noticed that the response includes a <script> tag. However, it appears that jQuery is stripping out this particular tag. Could this be considered typical behavior for jQuery or XHR, o ...

What is the proper method to set up jQuery in scripts loaded via AJAX? I keep receiving the error message: 'Uncaught TypeError: Object #<Object> has no method'

I have developed a website with an index page that contains a div for loading the content of each individual page. Initially, I included external JS files and performed initializations within each separate page. However, most of the time when the page loa ...