What is the best way to retrieve the height of a div that includes an image that has been

I have a script that inserts images into different columns. I want the script to insert images into the column with the smallest height. However, every time I try to check the height of the columns, it always returns 30px (likely because the images are not loaded yet).

Below is the code snippet:

<div id="diaporama-col1" class="col-xs-4">

</div>
<div id="diaporama-col2" class="col-xs-4">

</div>
<div id="diaporama-col3" class="col-xs-4">

</div>

.

var listImgDiaporama=["resources/img/img-1.jpg", "resources/img/img-2.jpg", "resources/img/img-3.jpg", "resources/img/img-4.jpg", "resources/img/img-5.jpg", "resources/img/img-6.jpg", "resources/img/img-7.jpg", "resources/img/img-8.jpg", "resources/img/img-9.jpg", "resources/img/img-10.jpg", "resources/img/img-11.jpg"];
function addImgToDiaporama() {


    for (i = 0; i < listImgDiaporama.length; i++) {

        var col1Height = $("#diaporama-col1").height();
        var col2Height = $("#diaporama-col2").height();
        var col3Height = $("#diaporama-col3").height();

        if (col1Height <= col2Height && col1Height <= col3Height) {
            $("#diaporama-col1").append("<img src=\"" + listImgDiaporama[i] + "\"/>")
        } else if (col2Height <= col1Height && col2Height <= col3Height) {
            $("#diaporama-col2").append("<img src=\"" + listImgDiaporama[i] + "\"/>")
        } else {
            $("#diaporama-col3").append("<img src=\"" + listImgDiaporama[i] + "\"/>")
        }
    }
}

Is there a solution to make this functionality work correctly?

Answer №1

One way to tackle this is by comparing the height of columns and adding images to the shortest one.

If you want to see it in action, check out the code snippet at https://jsfiddle.net/j9v5uwf2/1/

$('#addImage').click(function(){
  
  $shortest_column = getShortestColumn();
  $image = getRandImage();

  $($shortest_column).append($image);

});
function getShortestColumn(){

  var shortest_column = null;
  var shortest = 999999999;
  $(".column").each(function(){
    var height = $(this).height();
    if(height < shortest){
       shortest = height;
       shortest_column = $(this);  
    }    
  });

  return shortest_column;
}


function getRandImage(){
$rn = Math.floor(Math.random() * 50) + 1
  if ($rn = 1){$image = "<img src='http://lorempixel.com/200/100/'>";}
  else {$image = "<img src='http://lorempixel.com/200/150/'>";}
  
  return $image;
}
.column {
  width:30%;
  margin-left:1%;
  margin-right:1%;
  float:left;
  background: #222;
  text-align: center;
}
img {
  max-width:100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>


<div>
  <center><button id="addImage">Add Image</button></center>
</div>
<hr>
<div class="column" id="column1">
  <img src="http://lorempixel.com/200/100/">
  <img src="http://lorempixel.com/200/150/">
</div>
<div class="column" id="column2">
  <img src="http://lorempixel.com/200/150/">
  <img src="http://lorempixel.com/200/150/">
</div>
<div class="column" id="column3">
  <img src="http://lorempixel.com/200/150/" alt="">
  <img src="http://lorempixel.com/200/100/" alt="">
</div>

Answer №2

When inserting images in one js call, like looping through an array of images instead of clicking a button.

To demonstrate, I have added a delay between each image. You can remove it for live purposes.

https://jsfiddle.net/g6L7mbp7/3/

$numberOfImages = 5

// Creating an array of differently sized images
$images = [];
i = 0;
while (i < $numberOfImages ){
$images[i] = getRandImage();
  i++;
}

// Click the button to start inserting images
$('#addImage').click(function(){

$($images).each(function(index,image){
    
    
    // Remove the timeout for live use, included here for demonstration purposes
    setTimeout(function () {
    
    $shortest_column = getShortestColumn();
        $($shortest_column).append(image);
        
    }, index*500);
   
    
});
 
});

function addImage($image){
  $shortest_column = getShortestColumn();
  $($shortest_column).append($image);
}

function getShortestColumn(){

  var shortest_column = null;
  var shortest = 999999999;
  $(".column").each(function(){
    var height = $(this).height();
    if(height < shortest){
       shortest = height;
       shortest_column = $(this);  
    }    
  });

  return shortest_column;
}


   function getRandImage(){
   $rn = Math.floor(Math.random() * 10) + 1
   if ($rn % 2){$image = "<img src='http://lorempixel.com/200/100/'>";}
   else {$image = "<img src='http://lorempixel.com/200/200/'>";}
  
   return $image;
}
.column {
  width:30%;
  margin-left:1%;
  margin-right:1%;
  float:left;
  background: #222;
  text-align: center;
}
img {
  max-width:100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div>
  <center><button id="addImage">Add Images</button></center>
</div>
<hr>
<div class="column" id="column1">
  <img src="http://lorempixel.com/200/100/">
  <img src="http://lorempixel.com/200/150/">
</div>
<div class="column" id="column2">
  <img src="http://lorempixel.com/200/150/">
  <img src="http://lorempixel.com/200/150/">
</div>
<div class="column" id="column3">
  <img src="http://lorempixel.com/200/150/" alt="">
  <img src="http://lorempixel.com/200/100/" alt="">
</div>

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

When using angular.less, the @import feature is functioning correctly but a 404 error is displayed in the

Currently, I am working on a project using AngularJS along with angular.less. To centralize all my constants, I have stored them in one .less file and imported it at the beginning of all my other less files using a relative path: @import "constants" Even ...

Using Kendo UI Mobile, take advantage of a button to trigger the click action of another

Consider the following situation: HTML <a id="mButton" data-role="button" data-click="clickFn">myButton</a> <asp:ImageButton runat="server" ID="aspButton" style="display: none"></asp:ImageButton> SCRIPT function clickFn(e) { ...

How can I assign a class to my Typography component in Material UI?

When using my material-ui component, I wanted to add an ellipsis to my Typography element when it overflows. To achieve this, I defined the following styles: const customStyles = (theme) => ({ root: { textAlign: "left", margin: theme.spacing( ...

Ways to modify the color of table fonts and contents using inline CSS

I would like some help changing the color of the alphabet in my table. Here is the current format: <table border="1" background="images/haya1.jpg" cellpadding="5" cellspacing="10" width="30%" align="center" bordercolor="brown" bgcolor="red"> & ...

Troublesome Display of Badges in Bootstrap 5

My goal is to include a badge on a label, however all it does is change the text color to white <asp:Label CssClass="badge badge-pill badge-success" ID="Label1" runat="server" Text="Label"></asp:Label> ...

Show content when box is ticked

I am looking to display a row of text when a checkbox is checked, but I am finding it challenging as a beginner in this. Despite trying to understand other answers, I still struggle with the process. Here is what I have attempted so far: function RiskPl ...

Unable to use .ajax within autocomplete function

I've been struggling for days to make the jQuery autocomplete feature work. Currently, I am able to type in the textbox and see exactly what I want, but the issue arises when I click on the desired option - it does not show up in the textbox. I suspec ...

Leveraging route configuration's scope in HTML

As a beginner in AngularJs, I am currently exploring the creation of a single page application. However, I am encountering difficulties in converting my initial code into more professional and efficient code. During this conversion process, I have separate ...

The divide grew wider amongst the components

As I was working on a registration form, I noticed a sudden gap between two elements. To see the issue in action, you can check out my code here: http://jsbin.com/mujixepete/2/. Take a look at the gender and date of birth fields to understand what I ...

Modify the scrollbar's width, color, and corner radius to customize its appearance

Here is the table code where the styles are applied. By setting the tablecontainer height to 600px, we can make the table scrollable. However, I would like to customize the scrollbar with a different color, width, and corner radius. <TableContainer s ...

Error: Unable to instantiate a THREE.Scene object in Three.js due to TypeError

Recently, I decided to experiment with Three.js in order to incorporate it into a project of mine. However, upon running the initial example provided in the documentation: <html> <head> <title>My first Three.js app</title& ...

A guide on activating Effect in Div using just css

I have tried all the questions and answers related to this topic. Additionally, I attempted to solve related questions but was not successful. Please read my question thoroughly. What I Want: When I click on the click me Div, the second hiddendiv Div i ...

I'm encountering an issue with the dropify plugin where the data-allowed-file-

While using the dropify library to style file upload elements in my form, I ran into an issue with the data-allowed-file-extensions parameter not working as expected. Despite specifying allowed file extensions like "png jpg jpeg", the validation for input ...

Why is it necessary to use quotations and plus symbols when retrieving values of objects from JSON?

Initially, when attempting to call the PunkAPI for the first time, I was trying to include images (urls are an object returned in the JSON) by append("<img src='beer[i].image_url'/>"); Unfortunately, this did not work because (according t ...

Sorry, we couldn't find the page you were looking for. The request method used was GET and the request URL was http://127.0.0.1:

I've previously reported this error without success, so I'm providing more details now. I am new to coding and recently started a Django & Python project, but encountered some issues. Despite three weeks of troubleshooting, the problems persist. ...

Hovering over an option in Vue-Bootstrap b-select

I'm working with the Vue-Bootstrap framework and I need to update the CSS rule for the 'option' tag when it is being hovered over. Here is my code snippet: jsfiddle option:hover { background-color: red; } Can someone please explain why ...

Switch the background color of the body when hovering over a link

Is it possible to change the page background when hovering over a a using only CSS? I am searching for a solution that does not involve any JavaScript. I understand that we can access child elements with CSS, but I am unsure if it is possible to target th ...

Blending ThreeJS graphics with typical HTML/CSS pages

Is it feasible to swap out an animated image in the background of a website with JSON geometry while keeping the HTML elements in the forefront? I've attempted to utilize DOM Elements in ThreeJS without success. I experimented with incorporating my JS ...

The function jQuery.post is transmitting special characters encoded

After creating a string using recipeBlob = JSON.stringify(recipeData), I noticed that when sending it via $.post, the received data at my PHP script is showing up with escaped characters like this: {\"properties\":{\"Energy\":{\"v ...

Convert lengthy URLs in PHP into multiple lines

I need to display a lengthy string within a cell in a table, but the URL is too long. How can I convert something like this: /vlive.qqvideo.tc.qq.com/u0020mkrnds.p1203.1.mp4?vkey=7AB139BF6B32F537 47E8FF192E6FE557B3A3D644C034E34BF6EAEB4E0774F2A92EF3AC5C0075 ...