tips for personalizing your jQuery image preview script

Currently, I have implemented a jQuery script that allows me to preview multiple images before uploading them. Although the functionality works well, I am facing difficulties customizing it to meet my specific requirements.

 <script>

  $(document).ready(function(){

$(function() {
// Multiple images preview in browser
var imagesPreview = function(input, placeToInsertImagePreview) {

    if (input.files) {
        var filesAmount = input.files.length;

        for (i = 0; i < filesAmount; i++) {
            var reader = new FileReader();

            reader.onload = function(event) {
                $($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
            }

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

};

$('#product_sub_images').on('change', function() {
    imagesPreview(this, 'div.gallery');
  });
 });
});

</script>

In order to customize the image preview, I would like to:

  • Set a fixed width and height for images, such as 200px or display them as thumbnails using Bootstrap 4
  • Arrange the images in a single row with 10px padding on the left and right sides. If there isn't enough space, let the images wrap to the next row

Please note that I am implementing Bootstrap 4 in my code.

Answer №1

Below is an illustration of displaying images as background images, ensuring a consistent height and width. While this may result in cropping, it is necessary for maintaining a uniform size.

The code snippet is as follows:

$(function() {
  // Display multiple images preview in the browser
  var imagesPreview = function(input, placeToInsertImagePreview) {
    if (input.files) {
      var filesAmount = input.files.length;
      for (i = 0; i < filesAmount; i++) {
        var reader = new FileReader();
        reader.onload = function(event) {
          $($.parseHTML('<div>')).addClass('thumb-c').css('background-image', `url(${event.target.result})`).appendTo(placeToInsertImagePreview);
        }
        reader.readAsDataURL(input.files[i]);
      }
    }
  };

  $('#product_sub_images').on('change', function() {
    imagesPreview(this, 'div.gallery');
  });
});

Here's a testable snippet to view. The images are sized at 100x100 for better layout visibility, but you can adjust this in the CSS:

let imgs = [
    "https://via.placeholder.com/350x150",
    "https://via.placeholder.com/350x150",
    "https://via.placeholder.com/350x150",
    "https://via.placeholder.com/350x150"
  ],
  placeToInsertImagePreview = $('.gallery');

imgs.forEach(i => $($.parseHTML('<div>')).addClass('thumb-c').css('background-image', `url(${i})`).appendTo(placeToInsertImagePreview));
.thumb-c {
  width: 100px;
  height: 100px;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  border-radius: 4px;
  float: left;
  margin:0 10px 10px 0;
}
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

<div class='gallery'>

</div>

Answer №2

Avoid using the FileReader to read files as base64, opt for URL.createObjectURL instead

jQuery($ => {
  /**
   * Display multiple image previews in the browser
   * 
   * @param {HTMLInputElement} input
   * @param {string} placeToInsertImagePreview
   */
  function showImagesPreview (input, placeToInsertImagePreview) {
    for (const file of input.files) {
      $('<div>', {
        class: 'thumb-c',
        style: `background-image: url(${URL.createObjectURL(file)})`
      }).appendTo(placeToInsertImagePreview)
    }
  }

  $('#product_sub_images').on('change', function() {
    showImagesPreview(this, 'div.gallery')
  })
})

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

Unable to access component data while inside a v-for loop scope

I recently started using Vue and I'm having trouble accessing my component data within a v-for loop. After implementing the code below, I encountered this error message. TypeError: Cannot read property 'whatever' of undefined at eva ...

The anchor tag fails to trigger the onClick function in React

I'm having trouble updating the component state in my React app when clicking on an anchor tag within the render method. I've attempted to bind the function in the constructor, but the console.log statement is still not being called. Here's ...

The retrieval of data from AWS Dynamodb in Node.js is not done synchronously

I recently started working with Node.js and DynamoDB. I created a Node.js SDK to retrieve a single row from a DynamoDB table. The data is being fetched correctly, but there is a delay which is causing an error. Below is a snippet of my code: var AWS = re ...

What is the best way to send information to jQuery from an ASP.NET page?

There seems to be an abundance of resources discussing how to post data from jQuery to an ASP.NET page with AJAX, but I have not come across any for the reverse scenario. Can someone enlighten me on how to invoke a jQuery method from an ASP.NET page? ...

Angular 6 CSS spacing dilemmas

We recently made the switch from Angular 5 to Angular 6 and noticed that there is no spacing between the buttons/icons, etc. We are looking to bring back the spaces between the buttons and icons. I have recreated the issue below. As you can see in the Ang ...

Adjusting the line height of an inline-block div causes surrounding inline-block siblings to shift downward

As I venture into exploring the line-height property, I came across information on MDN which stated: For non-replaced inline elements, it determines the height used in calculating the line box height. However, in this scenario, when I set the line-heigh ...

Encountering a React JS error with Admin on Rest while making an API request

When making an API call (GET) with React.js using Admin on Rest, I encountered an issue. The server returns data when calling localhost:5001/cities, but there seems to be an error on the client side as indicated by the browser log: failure.js:18 Error: Th ...

Import the information into a td tag's data-label property

I have implemented a responsive table design that collapses for smaller screens and displays the table header before each cell. body { font-family: "Open Sans", sans-serif; line-height: 1.25; } table { border: 1px solid #ccc; border-collapse: co ...

Positioning the sDom in jQuery DataTables

Take a look at the image below: I want to adjust the position of the tableTools buttons (Copy, Excel, CSV) so that they appear aligned with the Search Box. I've experimented with different sDom parameters but haven't been successful. This is th ...

Looking to access XML file data using Vue.js on the server side?

I am trying to access an XML file located in a specific path on the server side using VueJS without using jQuery. Can you provide me with some ideas or advice? Scenario: 1. The file is stored at /static/label/custom-label.xml. 2. I need to read this file ...

Aligning a grid container in the middle

#panelb { background: lightblue; display: grid; grid-template-columns: repeat(auto-fit, 300px); } .card { background: gold; } .imgcard { display: block; width: 100%; margin: 0 auto; } <div id='panelb'> <div class=' ...

I need to know how to send a "put" request using JavaScript and Ajax

My task involves programmatically updating a spreadsheet using my code. I am able to write to a specific cell within the spreadsheet with the following function: function update(){ jQuery.ajax({ type: 'PUT', ...

Cloudflare SSL Error 522 Express: Troubleshooting Tips for Res

After setting up my express project using express-generator, I decided to make it work with a cloudflare SSL Certificate for secure browsing over https. My express app is running on port 443. Despite my efforts, when I try to access the domain, I encount ...

Issue with EJS template displaying no information

I am encountering an issue with ejs templates. While I have successfully used it in a previous project, in my current one, it's not working as intended. Instead of rendering the cards with the passed data, all I see is a blank page. Here is my code fo ...

Issue with Flask-Cors in Nuxt with Flask and JWT authentication implementation

I have exhausted all the available solutions to my issue, but I still can't seem to pinpoint the problem. Despite trying every solution out there, nothing seems to be of any help. Every time I make a request, the browser blocks it due to CORS Policy ...

Every iteration and vertical lines

<?php $arr = range(1,mt_rand(40,120)); ?> <table> <?php foreach ($arr as &$value) { echo '<tr><td>' . $value . '</td></tr>'; } ?> </table> This script generates a sequence of n ...

The execution of JQuery/Javascript is restricted to only the initial condition within a Visualforce page utilizing the apex:outputpanel tag

After using only JavaScript for some time, I decided to try out jQuery. However, I'm facing an issue with executing a jQuery function. It seems that only the first condition in my code (the first IF) is being executed, while the second one (the second ...

What is the best way to ensure my hover caption spans the entire size of the image?

I'm currently working on creating a hover caption that adjusts itself to fit the full width and height of an image even when it is resized. I attempted to implement a jQuery solution that I came across, but unfortunately, I am struggling to get it to ...

Setting up a CentOs Linux environment to host and run a node.js server

Just installed node.js on my new VPS server. I have written a basic script called "server.js" and it is currently running on port 8080. The location of the script is in the "var/www/html/" directory. However, whenever I try to access my domain, it only dis ...

Utilize Axios in Vue.js to fetch and process data from a REST API endpoint in C#

After successfully creating and deploying an API on Azure, I am trying to display the response in an alert box using javascript (Vue.js). The test method of my API returns the string "working". You can test the API here. This is the code snippet from my A ...