Using jQuery to locate the dimensions of an image and then adjusting the height and width of a div using

I'm currently working on a project where I need jQuery to determine the size of each image (approximately 8-10 images per page) within an Owl Carousel. However, every time I check in the developer tools, all I see is width: 0px, height: 0px

Here's how the elements look in the developer console:

<div class="item" style="width: 0px; height: 0px;">
    <img src="url.com/img.jpg" alt="">
</div>

This is the jQuery code I've been using:

$('.item').each(function() {
    var $this = $(this),
        w = $this.find('img').width(), 
        h = $this.find('img').height();
    $this.width(w).height(h); 
});

Can anyone provide guidance on how I can use jQuery to accurately retrieve the dimensions of the images as they load?

Answer №1

To ensure your script runs after all DOM elements have loaded, it's best practice to use the jQuery .ready() event.

Check out this Fiddle for reference

Here is a snippet of the code:

$(document).ready(function() {
  $('.item').each(function() {
    var $this = $(this),
      pic = $this.find('img');
    if (pic.load) {
      var w = pic.width();
      var h = pic.height();
      $this.width(w).height(h);

    } else {
      return;
    }

  });
  alert("width : " + $('.item').width() + " & height : " + $('.item').height());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="item" style="width: 0px; height: 0px;">
  <img src="http://dummyimage.com/190x100/000/fff.png
" alt="" />
</div>

Hopefully, this information proves helpful. Happy Coding :)

UPDATE::

There is another updated version available in this new fiddle

In this update, a dummy div element has been added with dimensions matching the item div.

Update #2:: It is important to wait until the image has loaded before running the script that determines its dimensions and applies them to the parent "item" div. To achieve this without waiting for the entire document DOM tree to be ready, you can utilize jQuery

.on("DOMready",".item img",function(){});
event function. This approach is similar to lazy-loading images.

Another update:: My answer has been further updated to consider scenarios where the image may not be fully loaded when the DOM is ready as discussed in the jQuery documentation for .ready() and .load() APIs.

Answer №2

Before querying for the height and width of an image, it is important to ensure that the image has finished loading.

Check out the code snippet below:

$(document).ready(function() {  /* Added this section */
  $('.item').each(function() {
    var $this = $(this),
      $img = $this.find('img');

      $img.load(function(){
         var w = $this.find('img').width();
         var h = $this.find('img').height();
        alert("width: " + w + ", height: " + h);
        $this.width(w).height(h)
      });

    ;
  });
}); /* Added this section */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="item" style="width: 0px; height: 0px;">
  <img src="http://dummyimage.com/190x100/000/fff.png
" alt="" />
</div>

The jQuery ready function triggers once the DOM is loaded, not necessarily ensuring all images have completed loading. Learn more here.

Answer №3

illustration: https://codepen.io/johnnydoe/pen/qpbGXY/

Give this a shot:

$('.element').each(function () {
    var $this = $(this);
    var picture = $this.find('img');

    if(!picture.length) return;

    picture[0].onload = function () {
        var width = image.width(),
            height = image.height();
        $this.width(width).height(height);
    }
});

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

Showcase items in varying positions on the page depending on the current time

I'm thinking about dynamically changing the position of an object on a webpage based on the time of day. For example, I want to display an image of the sun that moves across the page depending on the user's local time. Do you have any ideas or su ...

"Utilizing PHP and Ajax to generate an interactive table, the ability to input data is restricted to only the buttons that are visible on the screen or on

Let's Get straight to the point: I have successfully implemented a data table that dynamically fetches data from a database using PHP. The retrieved data is then inserted into the table. <?php $getAttendance = $functions->runSQL("dynamic dat ...

When using JavaScript, an error may occur that says "Cannot read property 'style' of null," but strangely, this issue disappears when the code is copied and

I seem to be encountering an error in my codepen and I can't figure out what I'm doing wrong. It appears that I may have misplaced something, but I would greatly appreciate any help or explanation of my mistake. function on() { document ...

jQuery ajax issue: Unable to locate file using relative path

I have recently transferred some script from an HTML document to an external file. I updated the jQuery path to point to the new location of the JavaScript file, but now it is unable to locate the necessary PHP file. Can anyone shed light on why this might ...

Position the div in the center and enhance the function to dynamically adjust when the user attempts to resize the window

var windowHeight = $(window).height(); var windowWidth = $(window).width(); var scrollTop = $(window).scrollTop(); var scrollLeft = $(window).scrollLeft(); jQuery.fn.center = function () { this.css("position","absolute"); this.css("top", Math.max( ...

Show a compact graphic in the upper-right-hand corner

Hey, I have this interesting idea but CSS isn't my strong suit. Any thoughts on how to achieve it? I'm looking to create a new class that, when applied to an item (like a div), displays a small clickable pre-defined image in the Top-Right corne ...

Troubleshooting media queries on an example webpage

Hey there! So, I'm having a bit of trouble with running media queries on a simple HTML page. It's been a while since I worked on this stuff, and I feel like I must be doing something silly that I can't quite pinpoint. If you want to take a ...

Excess spacing in image on top of CSS background overlay

While playing around with text scrolling over a fixed background image (similar to parallax scrolling but with no movement in the background), I encountered an issue. There seems to be a small margin or padding (around 5-10px) between the bottom of the upp ...

What could be causing React to display a TypeError: Unable to read 'join' property of an undefined value?

I am working on displaying a list of books with the names of their authors below. In cases where there are multiple authors, I am trying to separate their names using the .join() method. Below is a snippet of the code without using .join(): <select ...

When it comes to making ajax requests, I often find myself questioning when I need to use parseJSON and when

I have two different test applications that involve making Ajax requests. In the first one, I have to parse the ajax data.responseText before extracting the values, whereas in the second one, I can access the values directly. Here is a snippet of code fro ...

The module 'angular' could not be located and is causing an error

Currently, I am in the process of transitioning from Angular 1 to Angular 2 following this guide: . However, when I try to run the application using npm start, it displays an error saying 'Cannot find module 'angular''. This is a snipp ...

Exploring the process of searching for an id within an array of objects received through axios in Vue 2

I am currently working on verifying whether the user is included in the list that I retrieve using axios. However, I am facing an issue where the FILTER option I have used consistently returns undefined or [], even when the user does exist in the array. A ...

Order your custom tasks on Amazon Mechanical Turk directly through the web interface

Can I prompt the submission of a form on Mechanical Turk using a custom button instead of their designated 'submit' button? (I need to submit an empty form to speed up worker processing time) I attempted this: $('#mturk_form').submit() ...

The issue with passing data from Jquery Ajax to the action method

Below is the AJAX method being used: function SendMessage(contactId, e) { e.preventDefault(); var content = $("#text").val(); const dataObject = { contactId: contactId, content: content } ...

Unable to alter fxFlex property within Component using "setAttribute('fxFlex', '25%')" does not function properly in Angular 6

Currently, I am utilizing the flexLayout module to create responsive divs in my Angular application. You can find more information about flexLayout at https://github.com/angular/flex-layout and also at https://alligator.io/angular/flex-layout/. const nav ...

Is your SignalR chat struggling to establish a connection with the Hub?

I'm having trouble setting up a SignalR chatroom in asp.net, as I keep encountering the error message "Uncaught TypeError: Cannot read property 'chatHub' of undefined" and the chat prompt doesn't appear as expected. I followed this tuto ...

Caution CSS Division featuring an Icon

When completing a domain purchase, I designed a personalized warning message or division that appears during checkout. However, upon implementing my own CSS, The lock icon is supposed to appear on the left side of the text but instead displays inline. ...

What is the best way to wrap Bootstrap 5 columns according to the text inside them?

When using Bootstrap 5, is there a way for Bootstrap to arrange two rows with one column each if the text in one cell is wrapped and contains "My text" or "My other text"? <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi ...

What is the best way to use jQuery to listen for a container resizing event?

I am confident that I can achieve this: $(window).resize(function() {funkyfunc();}); The above code will execute funkyfunc() whenever the window is resized. However, my issue lies in wanting to resize one control after another has been resized. I've ...

The sidebar should remain fixed on top when viewed on mobile devices, but not when viewed on desktop

Prior to beginning a new project, I'm interested in exploring the possibility of implementing a sliding sidebar for mobile and tablets. On desktop, however, I envision a fixed sidebar that is part of the main container layout as shown below: <div ...