Tap on the image placeholder to replace it with your own image

Just starting out, I have the following HTML code within a <form>:

<div class="image-upload">
 <img id="send_photo_img1" src="assets/images/index2.png"/>
 <input id="send_photo_input1" type="file"/>
 <img id="send_photo_img2" src="assets/images/index2.png"/>
 <input id="send_photo_input2" type="file"/>
</div>

The goal is to allow users to click on the image (index2.png) with a "+" sign as a placeholder, which would then open a window like an input=file, allowing the user to choose an image to replace the placeholder.

Here is the rest of the code:

Jquery function inspired by @Ivan Bayev's answer here:

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").click(function(){
    $("#send_photo_input1").trigger("click");
    $("#send_photo_input1").change(function(){
        readURL(this);
    });         
});

CSS styling:

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

While the code works, I'm not completely satisfied with (1) the use of jQuery and (2) the loading time once the image replaces the placeholder. The "loading" sign remains for about 30-40 seconds before disappearing.

Any advice or suggestions are greatly appreciated. Thank you!

Answer №1

If you're looking for a solution to the problem mentioned earlier, look no further.

Firstly, it's not ideal to attach code to IDs when dealing with multiple instances of input=file on a single page. It's better to use classes instead. Each block should resemble this:

<div class="image_upload">
 <img class="upload_image" src="assets/images/picture.png"/>
 <input class="file_input" type="file"/>
</div>

Then, you'll need some jQuery workaround to select it:

$(".image_upload img").click(function(){
    var imageDiv = $(this).next(".file_input");
    imageDiv.trigger("click");
    imageDiv.change(function(){
        //console.log('Use this to track results');
        //your function goes here.
    });
});

CSS:

.image_upload input
{
    display: none; // hides the original input
}
.image_upload img
{
    width: 90px;
    height: 90px;
    cursor: pointer;
}

The ReadURL function in my query works perfectly well, just make this adjustment:

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

change to:

reader.onload = function (e) {
   $(input).prev(".upload_image").attr('src', e.target.result);
}

And remember, I'm using prev(), but you could opt for a more general approach:

 $(input).parent().find(".upload_image").attr('src', e.target.result);

Consider using an icon instead of an image for a better visual impact.

This response aims to provide you with a functional code snippet for the issue at hand. Don't hesitate to reach out for more details if necessary.

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

Eliminate spacing between divs of varying heights

I'm facing an issue with my small gallery of images. Despite having the same width, they vary in height causing the second row to start below the tallest image from the previous row. How can I eliminate these empty spaces while still maintaining the v ...

Text that spans across multiple lines

I have a multi-line text that I need to adapt to a div. For example: https://i.stack.imgur.com/mtZmf.png Is there a way to adjust the text within the div? Can we prevent the blue spacing after the word "text" using CSS? If I have various texts of differ ...

The left side of the form input material is obscured unless the necessary criteria are fulfilled

I am currently in the process of developing the front-end for a web application using the material library. The issue I am facing is that when a field does not meet its requirements, such as needing to enter a 'bedrijfsnaam', the border turns red ...

Is there a way to incorporate jQuery validation similar to MVC data annotation?

In my MVC project, I have a master/details view page. The Details section is actually a partial view containing input fields and a save button displayed below. <button type="button" id="btnAddDetails" class="btn btn-primary">Add Details <span cl ...

Incorporating hyperlinks within the navigation buttons

I'm working on a design where I have six buttons that need to be displayed on top of a background image. How can I ensure that the text inside the buttons stays contained within them? Here is the current code structure I am using, which involves utili ...

What is the best way to horizontally center my HTML tables and ensure that they all have uniform widths?

I'm currently facing an issue where I'd like to center align all tables similar to the 'Ruby Table.' However, I'm unsure of how to achieve this. You may also observe that some tables have varying widths. What CSS rule can I apply ...

I'm struggling to locate the space that should be between these elements

After accidentally starting in quirks mode without declaring a doctype, I realized my mistake and corrected it by declaring a doctype. However, there is a persistent issue with a space between .car-box-img and car-box that I can't seem to locate in t ...

Is there a way for me to attach a link to a picture displayed in a lightbox that directs to an external ".html" file?

I have a platform where users can view images in a gallery and when they click on an image, it opens up in a lightbox. I am trying to add a feature where the opened image can be clicked again to redirect the user to an external page. I attempted to nest t ...

Clicking on the overlaying divs in the slideshow does not trigger any changes when clicked

My question is about the behavior of the href attribute in a fade-style animation. Even when different containers are visible, the href value remains constant. Below is the HTML code: <div id="teaserslider"> <ul> <li> ...

Performing a jQuery ajax request on data that has been dynamically loaded using

I am currently in the process of constructing a form for users to make reservations on a website. I have successfully set it up so that when a user selects a shift, the available dates are populated. Now, my goal is to have the available seats load when a ...

What steps can be taken to initiate validation when a user deletes the initial field value?

I have a solid understanding of the lazy behavior exhibited by JQuery validation. In reality, it's actually only partially lazy - if a field starts with a valid value, loses focus, and then is changed to an invalid value, an error message shows up imm ...

Using jQuery bootgrid: Sending PHP data through AJAX

I'm currently using the jQuery bootgrid along with AJAX for server-side processing. I am attempting to pass a PHP variable to the processing script through AJAX, but unfortunately, I haven't been successful in getting it to work. Here is the cod ...

Top method for converting scrolling into an element

When trying to create a scrollable element, I attempted the following: .scroll-content { overflow: hidden; } .scrollabe { overflow-y: scroll; } <ion-content> <ion-grid style="height:100%" *ngIf="plat && ticket"& ...

What could be causing my dropdown menu to vanish unexpectedly after being clicked for the first time?

To view the live demonstration, simply click here. I have an issue with my drop down menu where it is hidden upon first click. Additionally, I would like the drop down menu to disappear when clicked anywhere outside of its current display. How can I accomp ...

Does CSS media query "@media only screen" only work when I am resizing the window?

I recently encountered an issue with the code found on this website (the repository can be viewed on Github here): @media only screen and (max-width: 600px) { img {width: 100%; height: 100%; margin: 0; padding: 0; } a.box { width: 100%; pa ...

What is the best way to trigger a controller action using jQuery in your application.js file?

Currently, I am incorporating the jQuery autocomplete plugin into my project and looking to personalize a specific event: select: function(event, ui) { $('.topic_field').val(ui.item.topic.name); return false; This event es ...

Adjust the text to fit neatly within a circular-shaped column container

I am currently working with Bootstrap 5 and I have a row with two columns positioned next to each other. My goal is to apply rounded borders to the left column while ensuring that the content remains within the div. Below is the code snippet: <div clas ...

Mobile.changePage does not trigger the pageinit event in jQuery Mobile

I've encountered an issue with handling the on-click event of a button in the following code snippet: $(document).on("click", '.submit_review_button', function(event, ui) { var place = $.data(this, "object"); var ttext = $("#revie ...

Create a table by incorporating the information from the page along with additional content

I need to extract the data from a list and convert it into a table, add some additional content that I will provide, and then align the table accordingly. While I can easily align elements and already have the list, I am facing difficulty in converting it ...

Second word in the textbox receiving attention

When I type in the text box, it always focuses on the second word instead of the first word. If I set Maxlength=1, it doesn't allow me to type. I have to press backspace before typing. Can anyone help me with this issue? Below is my code: <input ...