JavaScript image element loaded but still has a height of 0

This particular issue is causing frustration as it seems to only work with a specific set of images and not with others.

The object in question is:

function PreLoader(toLoad, parent, images) {
  var errored = 0;
  var loaded  = 0;
  var toLoad  = toLoad;

  function allLoaded() {
    // reset the counters so it can be used again
    loaded  = 0;
    errored = 0;

    // determine which img is the tallest
    var l = 0;
    for (var i = 0; i < images.length; i++) {
      l = (l > images[i].height()) ? l : images[i].height();
    }

    // set the height of the container to the tallest
    // unless it's already bigger
    // height() is from jQuery
    if (parent.obj.height() < l)
      parent.obj.css("height", l);
  }

  this.load  = function() {
    ++loaded;
    if (loaded + errored == toLoad)
      allLoaded();
  };

  this.error = function() {
    ++errored;
    if (loaded + errored == toLoad)
      allLoaded();
  };
}

The method of implementation has been similar to the following:

var parent = {obj: $("#some-img-container")};
var slabLoader = new PreLoader(2, parent, [external.slab, internal.slab]);
external.slab.src = "2.png";
external.slab.onload  = slabLoader.load;
external.slab.onerror = slabLoader.error;
internal.slab.src = "1.png";
internal.slab.onload  = slabLoader.load;
internal.slab.onerror = slabLoader.error;

The challenge arises when this approach does not consistently provide the desired outcome. There are multiple image sets that are absolutely positioned due to being layered on top of each other, resulting in varying heights. Hard coding the heights is not feasible as they are unknown prior to page load, and absolute positioning does not impact their parent elements' size, making methods like height: 100% unreliable.

In certain instances, the variable l in the allLoaded() function returns 0 even though the images should have finished loading by then.

Is my assessment accurate or am I overlooking something that could explain why it occasionally succeeds?

The corresponding HTML structure appears as follows:

<div class='wrapper-hover'>
  <div class='wrapper-content'>
    <a herf='#' id='some-img-container' class='viewport'>
      <!-- this is where the image goes, added by the script -->
    </a>
    <div class='wrapper-caption'>
      <label class='wrapper-caption-content'>Some Image</label>
    </div>
  </div>
</div>

I apologize if the inquiry is somewhat challenging to decipher.

UPDATE:

Using .naturalHeight instead of jQuery's .height() retrieves the actual image height on disk rather than its scaled CSS height (width: 100%) but still fails to address the zero height returned for some images previously.

All images indicate .complete as true before attempting to access their heights.

Answer №1

Check out the updated version of the resize function below:

function adjustSize( container, pics ) {
  // Keep track of the tallest image's height.
  var largest = 0;

  // Iterate through all images to find the tallest one.
  for ( var j = 0; j < pics.length; ++j ) {

    // Assign the current image to a variable for quicker access.
    var current = pics[j];

    // Check if the image is visible to the user.
    if ( current.offsetParent !== null )

      // Compare the height with the current tallest image,
      // update if necessary.
      largest = ( largest > current.height ) ? largest : current.height;
  }

  // If the tallest image's height is 0, it means all images are hidden
  // and resizing can be skipped.
  if ( largest === 0 )
     return;

  // Set the container's height to match the tallest image,
  // ensuring the parent resizes even when the window shrinks.
  // Adding 2 pixels for good luck!
  container.setAttribute( "style", "height:" + (largest + 2) + "px" );
}

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

angular primeng table has a checkbox to select all checkboxes

Is there a way to check all checkboxes in a table when the checkbox in the table header is clicked? I am currently utilizing angular 12 and primeNG table for this functionality. <p-table styleClass="text-sm" [value]="value" [loading] ...

I am encountering an error message that states "Uncaught TypeError: Cannot read property 'use' of undefined."

https://i.sstatic.net/HcwYr.png Error: Unable to access the 'use' property of an undefined object ...

Explanation: The information box does not appear when the mouse hovers over it

Welcome to the gallery showcasing a unique calendar design with tooltip functionality. This calendar features a special hover effect for New Year's Day on January 1st, displaying a tooltip text upon interaction. Feel free to explore the code below to ...

Unable to access a nested JSON object that has a repeated name

I'm relatively new to working with JSON, so the issue I'm facing may be simple, but I haven't been able to find a similar problem on stackoverflow. Here's my question: My goal is to access a nested JSON object like: pizza.topping.ratin ...

Creating a tree with branches using divs: a comprehensive guide

I have been tasked with designing a tree structure for a project that will visually represent the results of a quiz. The tree needs to have branches on both sides, featuring 4 main branches, each with 5 smaller branches extending from them. Additionally, I ...

Selecting specific elements based on their position within a parent element using

I can't seem to figure out the strange behavior of the nth-child selector. After calling the function BackColor1(), my visual appears different than expected: Something seems off. However, when I call BackColor2(), everything looks normal again. Co ...

The expected number of calls for the callback function was not met

Our employee webpage is designed to make Ajax calls to the node.js web server in a continuous loop. The problem arises when the callback UpdateTeamArr is expected to be triggered multiple times based on the loop max and the number of department options a ...

Ways to prevent the datalist from appearing in the source code

Is there a way to hide a long list of words from appearing in the source code when viewing using PHP or HTML? Below is an example of the code I am working with: <label for="country_name">Country : </label><input id="country_name" name="cou ...

Utilizing a foundational element to automatically unsubscribe from multiple observable subscriptions

Within our Angular application, we have implemented a unique concept using a Base Component to manage observable subscriptions throughout the entire app. When a component subscribes to an observable, it must extend the Base Component. This approach ensures ...

Menu Tabs with Rounded Edges

Seeking help to round the corners of a tabbed dynamic menu using Drupal and the dynamic-persistent-menu module. The code provided below is almost perfect, with 99% accuracy. View the current state of the menu here: . Can anyone assist in achieving the rema ...

Encountering `No provider for ControlContainer!` error while utilizing [class.someClass] in Angular 2?

I have a project in progress which involves using angular 2. I am currently working on forms and validation and have encountered an issue. Although I have found a workaround, I am curious to understand why my original code is not functioning properly. Bel ...

Ways to adjust the text size in jqGrid?

The current theme is ui-lightness. How can I adjust the font size within the grid? Your suggestions are appreciated. Many thanks. ...

Issues with AngularJS Validation not functioning properly with File Inputs marked as 'Required'

I've been experimenting with this issue and haven't been able to solve it. While creating an Angular form, I found that validation works fine when the required attribute is used in a text field. However, when I tried adding a file input type with ...

Learn the process of transferring data-target IDs to another JSP using Bootstrap

Currently, I am encountering an issue where I am trying to use bootstrap to display a dialog box by clicking on a button. The dialog box is created in HTML (.jsp) and the submit button is in another .jsp file. However, when I click on the button, instead o ...

Create an input box with a designated class

When I click the button in my HTML and JavaScript code below, I am able to dynamically add a text field and radio button. This functionality is working properly. However, I also want the newly generated text field to have the same font size and appearance ...

How can you tell if a contenteditable div is currently in focus?

Essentially, my setup consists of: HTML: <div class="div1"> <div class="as-text-box" contenteditable="true"></div> </div> CSS: .div1{ position:absolute; height:50px; width:200px; background:white; border:1px solid #c ...

Sorting algorithm for basic leaderboard using bubble sort

I'm in the process of developing a basic video game leader board that will arrange user scores against preset scores in descending order. <html> <!Foundation Page for building our Javascript programs> <head> <title>The ...

From JSON to JavaScript transformations

Currently, I am attempting to utilize JSON with data retrieved from the server by implementing this PHP script: include("db_connect.php"); mysql_connect($host,$username,$password); @mysql_select_db($database) or die( "Unable to select database"); $resu ...

The HTML table fails to refresh after an Ajax request has been made

I am currently utilizing Ajax to delete a row from the Roles table. The functionality allows the user to add and delete roles using a link for each row. While the deletion process works properly and removes the row from the database, the table does not get ...

What could be causing jQuery to overlook dynamically loaded jQuery Mobile buttons?

While working with a web page that uses jQuery Mobile, I utilized Ajax to load the following HTML content. The key detail is the presence of the onButton class attached to the anchor tag. <a class="onButton ui-btn ui-btn-inline ui-btn-corner-all ui-sha ...