Tips for showcasing an image prior to uploading within a personalized design input file

I am facing an issue with displaying multiple images inside custom style input file labels before uploading them to the database. Currently, the script I am using only displays one image at a time and in random positions. My goal is to have each image appear neatly inside its corresponding label. However, for some reason, the images are not being displayed correctly within the labels. Can anyone help me identify what might be causing this problem?

Answer №1

The image appears in the last position because your readURL function is overwriting the .onload property, storing only the last value (which points to #photo4):

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

            // You are setting the value of 'onload' property here...
            reader.onload = function(e) {
              $('#photo1').attr('src', e.target.result);
            }

            // Here, you overwrite the last value and store a new one...
            reader.onload = function(e) {
              $('#photo2').attr('src', e.target.result);
            }

            // Overwriting the last value and storing a new one...
            reader.onload = function(e) {
              $('#photo3').attr('src', e.target.result);
            }

            // This function will run when the load event of the reader fires
            // as it's the last value stored in the property:
            reader.onload = function(e) {
              $('#photo4').attr('src', e.target.result);
            }
            reader.readAsDataURL(input.files[0]);
          }
        }

Furthermore, each input type=file element has the same id, which is not recommended. All ids should be unique.

To simplify your code, we can reduce it to this working version:

// Set up the same event handler for all input type=file elements
$(".file").on("change", function(e) {
  if (this.files && this.files[0]) {
    var reader = new FileReader();
      
    // Use W3C DOM Event Standard for event listeners
    reader.addEventListener("load", function(evt) {
      // Set the src attribute of the next sibling element
      e.target.nextElementSibling.setAttribute('src', evt.target.result);
    });
    
    reader.readAsDataURL(this.files[0]);
  }
});
.col-md-4 {
  width: 33.33333333%;
  display: inline-block;
  margin-bottom: 15%;
}

.labelav.largeFile:after {
  ...
}

.labelav.largeFile:hover:after {
  ...
}

.labelav.largeFile input.file {
  visibility: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <div class='col-md-4'>
    <label class="labelav largeFile" for="file1">
      <input type="file" id="file1" class="file img1" name="photo1">
      <img id="photo1" src="#" alt="">
    </label>
  </div>

  <div class='col-md-4'>
    <label class="labelav largeFile" for="file2">
      <input type="file" id="file2" class="file img2" name="photo2">
      <img id="photo2" src="#" alt="">
    </label>
  </div>

  <div class='col-md-4'>
    <label class="labelav largeFile" for="file3">
      <input type="file" id="file3" class="file img3" name="photo3">
      <img id="photo3" src="#" alt="">
    </label>
  </div>

  <div class='col-md-4'>
    <label class="labelav largeFile" for="file4">
      <input type="file" id="file4" class="file img4" name="photo4">
      <img id="photo4" src="#" alt="">
    </label>
  </div>
</form>

Answer №2

After receiving input from Scott Marcus, I have compiled a comprehensive response to address my question without duplicating any information. In addition to resolving javascript concerns, I also encountered display issues that required adjusting pixel dimensions in the code. Interestingly, I had to modify certain aspects of the code within my program for the snippet to function correctly...

Here is the revised solution:

  
  // Avoid setting up redundant event handlers individually
// This script allows all input type=file elements to share
// the same change event handling function. The parameter 'e' represents the
// change event:
$(".file").on("change", function(e) {
  if (this.files && this.files[0]) {
    var reader = new FileReader();
      
    // Utilize W3C DOM Event Standard for event listener setup
    // instead of using `onclick`, `onload`, etc. properties. One universal
    // function can now handle events for any input type=file clicked
    // Here 'evt' denotes the load event of the reader
    reader.addEventListener("load", function(evt) {
      // Update src attribute of next sibling element
      // with respect to the changed input:
      e.target.nextElementSibling.setAttribute('src', evt.target.result);
    });
    
    reader.readAsDataURL(this.files[0]);
  }
});
.col-md-4 .labelav.largeFile{
    width:33.33%;
  display: inline-block;
  margin-bottom: 10%;
    border-radius: 10px;
  border: 5px dashed #ccc;
 min-height:200px;
      cursor:pointer;
    background: url("http://www.startuppassion.eu/wp-content/uploads/2017/03/plus-sign.png") no-repeat center;
        background-size: 40%;
}
.labelav img{
    width:30%;
    position:absolute;
    left:20px;
}
.labelav.largeFile img:after {
  width:100% !important;
  display:inline-block;
    max-width:100%;
}
.labelav.largeFile input.file {
width:0px;
height:0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <div class='col-md-4 imgblock'>
    <label class="labelav largeFile" for="file1">
      <input type="file" id="file1" class="file img1" name="photo1">
      <img id="photo1" src="#" alt="">
    </label>
  </div>

  <div class='col-md-4 imgblock'>
    <label class="labelav largeFile" for="file2">
      <input type="file" id="file2" class="file img2" name="photo2">
      <img id="photo2" src="#" alt="">
    </label>
  </div>

  <div class='col-md-4 imgblock'>
    <label class="labelav largeFile" for="file3">
      <input type="file" id="file3" class="file img3" name="photo3">
      <img id="photo3" src="#" alt="">
    </label>
  </div>

  <div class='col-md-4'>
    <label class="labelav largeFile" for="file4">
      <input type="file" id="file4" class="file img4" name="photo4">
      <img id="photo4" src="#" alt="">
    </label>
  </div>
</form>

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

Stop the reloading of the parent page when the exit button is pressed on the popup screen

I have set up a modal popup that appears when a user clicks on a specific link. Inside the popup, I have included an exit button to close it. However, I am facing an issue where clicking on the exit button not only closes the popup but also reloads the par ...

Storing a portion of JSON data within a function called in the HTML document

I've been working with Angular and need to save a portion of JSON data in a variable within a function that is called in an HTML file: <select id="postazione" onchange="postazioneSelezionata()"> <option value="" selected disabled >Cho ...

Having trouble displaying WordPress posts in a grid view on a single page

Currently, I am working on customizing a Wordpress theme that features a grid view. My goal is to dynamically load posts on the same page, similar to how it works on Twitter. I have experimented with various plugins such as infinite scroll, but unfortunate ...

How to extract the values of the parent for a specific child within an array of nested JSON objects?

Take a look at this snapshot of my JSON data. const info = [{ "employees": [ { "employee": [ { "name": "Jon", "surname": "Smith&quo ...

How to Reference a Local File in PHP using Zend Framework for jQuery's .Load Function

I'm currently working on a PHP Zend framework website and I'm trying to link to a local file. The file structure is as follows: public_html/application/views/index/filename1.phtml Within filename1.phtml, I want to make a jQuery call to load a ...

Prevent scrolling/touchmove events on mobile Safari under certain conditions

iOS 5 now supports native overflow: scroll functionality. I am trying to implement a feature where the touchmove event is disabled for elements that do not have the 'scrollable' class or their children. However, I am having trouble implementing ...

The MUI next Tooltip fails to display upon hovering

While using Material-UIv1.0.0-beta.34 Tooltip with Checkbox and FormControlLabel, I noticed that the tooltip works as expected when hovering over the label in one case. However, when I tried creating a new component(custom) with FormControlLabel and Checkb ...

Utilizing useEffect Hooks to Filter Local JSON Data in React Applications

For my engineering page, I have been developing a user display that allows data to be filtered by field and expertise. Fields can be filtered through a dropdown menu selection, while expertise can be filtered using an input field. My initial plan was to ...

What is the best way to ensure the box div is centered responsively?

Here is the code for my HTML file: body { background-color: rgb(231, 59, 59); font-family: "Alata"; font-size: 20px; margin: 30px; } h1 { margin-top: 100px; color: #202124; text-align: center; } .box { width: 1000px; } input { positi ...

Request for a new login using credentials via ajax

We've set up a web application on a LAMP(PHP) system that makes around 40 Ajax calls. Users are tracked using PHPSessions with a 1 hour cookie lifespan (which we want to maintain for quick expiration). ISSUE: If a user is inactive for the full hour an ...

Create a JavaScript function that accepts an argument and can be called both with and

Does anyone know how this code works? function animate(t) { sun.rotation.y = t/1000; renderer.clear(); camera.lookAt(sun.position); renderer.render(scene, camera); window.requestAnimationFrame(animate, renderer.domElement); ...

Ways to change the URL post saving a cookie with express?

I have written this code for user login in my Express router: if (password === realpassword) { res.cookie('thecookie', 'somethingliketoken'); res.redirect(302, '/somepages'); } else { res.status(403).end(); } The ...

Having difficulty creating a simple HTML menu, where one button is visible but the other is unresponsive despite having identical CSS styling

Looking to enhance my HTML skills as a beginner, I've begun building a simple website and am currently focusing on the menu. I created a "home" button (which is visually there but not functional), and then attempted to create another button next to it ...

AngularJS causing issues with Materializecss dropdown menu operation

I'm currently working on a web application using Materializecss and AngularJS for the front-end. However, I've encountered an issue with the dropdown menu component of Materialize not functioning as expected. Here's an example of the dropdo ...

Showcase big image upon hovering mouse with automatic positioning on Magento

As a newcomer to magento, I am interested in adding an effect that displays a large image when hovering over it with the mouse. This feature should automatically position itself on the product listing page in magento. Your assistance is greatly appreciate ...

The icons from MaterializeCSS are not displaying correctly on the navbar within an Angular 7 project

Having an issue implementing MaterializeCSS Icons on the navbar. The arrow-drop_down icon is not displaying correctly, showing only text instead. Oddly enough, the icons render properly on other pages except for the app.component.html file. I attempted to ...

Retrieve and manipulate the HTML content of a webpage that has been loaded into a

Hey, let's say I have a main.js file with the following code: $("#mirador").load("mirador.html"); This code loads the HTML content from mirador.html into index.html <div id="mirador"></div> I'm wondering if there is a way to chan ...

What is the best way to include a span within a select option element to display a flag beside each option?

I'm currently working on a dropdown menu that allows users to easily select their preferred language. I'm facing an issue with incorporating flags using https://github.com/lipis/flag-icon-css for each option. Can someone please assist me with thi ...

What alternative to tables can I utilize that possesses similar attributes?

I have a collection of images all with the same size that I want to use for a slideshow. I would like them to be displayed in a single row, potentially wider than the window itself, and I prefer some of the pictures to extend off the screen rather than wra ...

Position footer at the bottom of the webpage and adjust the height to be filled with main content using Bootstrap 4

I am currently in the process of designing a bootstrap layout that includes a header navbar along with a footer. My goal is to ensure that the footer is always at the bottom of the page, even if there is limited content. Here's what I have implemente ...