Troubleshooting: Why is Jquery unable to retrieve image height?

Having trouble using jQuery to find the actual height of the first image nested within a container. I can access the src attribute but not the height. Any suggestions on how to get the accurate height? Is it necessary to retrieve heights via CSS? Unfortunately, setting width and height in the img tag is not an option for me.

 $(document).ready(function() {
       var imageContainer = '#image-container';


       var imageSrc = $(imageContainer).children(':first').children(':first').attr('src'); // control test
       var imageHeight = $(imageContainer).children(':first').children(':first').height(); // have also tried attr('height')

       alert(imageSrc + ' ' + imageHeight);

    });


    <div id="image-gallery">
      <div id="image-container">    

        <div class="slide">
          <img src="test1.jpg" alt="test1" />
          <p>
            <strong>This is a test 1</strong>
          </p>
        </div>

        <div class="slide">
         <img src="test2.jpg" alt="test2" />
         <p>
           <strong>This is a test 2</strong>
         </p>
       </div>

      </div>
    </div>

Answer №1

According to information found in the API documentation:

If your code depends on assets being loaded (for example, if you need the dimensions of an image), it is recommended to place the code inside a handler for the load event instead.

Therefore, instead of running your script within $(document).ready();, consider using $(window).load(); or even better, $(image).load();. Here is an example:

$(document).ready(function() {
    var imageContainer = '#image-container';

    $(imageContainer).children(':first').children(':first').load(function() {
        var imageSrc = $(this).attr('src'); // test
        var imageHeight = $(this).height(); // also tried attr('height')

        alert(imageSrc + ' ' + imageHeight);
    });
});

Answer №2

It is recommended to hold off until your picture loads completely. Something similar to the following code:

 $('#imageContainer').children(':first').children(':first').load(function() {
     alert($(this).height());
 });

Answer №3

The issue concerning not obtaining the image sizes is due to the fact that the images have not been assigned any size at that point in time. The script is executed after the webpage has finished loading, but before the images have been fully loaded.

To address this problem, execute the portion of the script that requires the image size only after all elements on the page have been successfully loaded:

$(window).load(function () {
  ...
});

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

What is the purpose of mapping through Object.keys(this) and accessing each property using this[key]?

After reviewing this method, I can't help but wonder why it uses Object.keys(this).map(key => (this as any)[key]). Is there any reason why Object.keys(this).indexOf(type) !== -1 wouldn't work just as well? /** * Checks if validation type is ...

Having trouble with the jQuery each function's functionality

I am creating circular counters for surveys by generating a counter for each answer option. Currently, I am utilizing this "plugin": Issue: The problem lies in the plugin not fetching the text value from the <div> element and failing to draw coun ...

What are the steps to apply a custom style to a selectmenu in jQuery Mobile while setting $.mobile.linkBindingEnabled to false

We are in the process of building a mobile application with PhoneGap and Backbone.js. All guides suggest setting $.mobile.linkBindingEnabled = false; to allow Backbone's router to handle hashtag changes effectively. However, while this method works w ...

Finding the ID of a dropdown located within a gridview

I am facing an issue with a dropdown inside a gridview where I am trying to retrieve the ID of the dropdown. However, I am encountering an object reference error. Even after attempting the code below, it still throws an error regarding object reference d ...

Interactive radio button that only registers the most recent click

Homepage.jsx const Homepage = () => { const [categories, setCategories] = useState([]) const [products, setProducts] = useState([]) const [selected, setSelected] = useState("all") const getAllCategories = async() => { try{ ...

Using a custom filter in AngularJS allows for seamless data filtering directly from the initial dataset

My goal is to implement a custom filter that will allow me to filter data based on a search word. The scope attribute gets populated in the controller's scope as shown below: naApp.controller('naCareNewTicketCtrl', ['$scope', &apo ...

Design a captivating Profile Picture form using HTML and CSS styling

In my form, I am looking to include a user's Profile picture which should be displayed in either a circular or rectangular shape. Initially, the image area will show a black background or a placeholder image. When the user clicks on this area, they sh ...

Looking to migrate my current firebase/react project to typescript. Any tips on how to batch.update?

Having difficulty resolving a typescript error related to batch.update in my code. const batch = db.batch(); const listingDoc = await db.collection("listings").doc(listingID).get(); const listingData = listingDoc.data( ...

Guide to Embedding an Image in a List in HTML

How do I resize an image according to the size specified in CSS, and ensure that it fits within a list of items where each item consists of both an image and a name? Currently, my code only displays the image in its original size. for(var i =0; i< o ...

Click to open a Swipeable Drawer using an onClick event handler in Material UI

Issue Encountered: Currently, in the provided documentation code (https://codesandbox.io/s/cnvp4i?file=/demo.tsx), the drawer opens when the "Open" button is clicked at the top. However, I am looking to have the drawer triggered and opened when it is direc ...

Troubleshooting Bootstrap 4 Content Alignment Issue: Centering Horizontally and Vertically

Having trouble centering my content both vertically and horizontally within the body of the webpage using Bootstrap 4. Despite trying various solutions from the documentation and StackOverflow, I can't seem to get it to work. Would greatly appreciate ...

Retrieve data from a REST API in a dynamic manner without manually specifying the table structure in the HTML code

I am looking to retrieve JSON data via a post request from a REST API: http://localhost/post1 param1='1' The response will look like this: { "json_table": [ { "date": 123, "test": "hello2" }, { "date": 19, ...

Can a single-page application be created using Express without utilizing React, Angular, or similar frameworks?

Our codebase is currently exclusively built on express, and we are looking to expand it while transitioning into a single page application. At this point in time, I am hesitant to rework the code using frameworks such as Angular or React to achieve this go ...

The Controller is encountering an empty child array when attempting to JSON.stringify it

After examining numerous similar questions, I am uncertain about what sets my configuration apart. I've experimented with various ajax data variations and JSON formatting methods, but the current approach seems to be the closest match. This issue is ...

Alter the background color of a table cell in Angular HTML depending on a boolean value

Attempting to use Angular ng-class to set the background color of a table cell. I'm referencing code snippets from these resources: Angular: How to change the color of cell table if condition is true Change HTML table cell background color using ...

Update the content of a div element with the data retrieved through an Ajax response

I am attempting to update the inner HTML of a div after a certain interval. I am receiving the correct response using Ajax, but I am struggling to replace the inner HTML of the selected element with the Ajax response. What could be wrong with my code? HTM ...

Strip certain tags from HTML without including iframes

Removing specific tags from HTML can be tricky, especially when working with PHP and JavaScript. One approach is to fetch an HTML page in a PHP file using curl and getJSON, storing the result in a .js file. However, this method may encounter issues with mu ...

Issue with file upload using Ajax FormData [JQuery] [PHP]

I've been encountering an issue with my upload form - every time I submit it, the PHP file runs but my $_FILES variable ends up empty. I've been spending hours trying to troubleshoot this problem, and despite scouring through numerous posts on th ...

Event listener is failing to execute the functions

Even though the inline onmouseover="verdadero()" function is properly set up Upon further inspection, it appears that while the event listener is added to the box element, the function is not being triggered when hovering over it, and console.lo ...

What is the best way to change the folder name when hovering over it?

Typically, my website displays categories with images from the /thumb-min/ directory. For example, 95-IMG_6509.JPG is loaded like this: /thumb-min/95-IMG_6509.JPG When I navigate to the details page, it loads the image from: /thumb-medium/95-IMG_6509.JP ...