I'm trying to use jQuery to find the image height of the first "grand children" of a container, then set the container to that height. But, I can't seem to pull the image height attribute - getting the src works. Any ideas? Is it just trying to pull the heights via CSS? How do i get the "real heights" I can't input the width and height in img tag - so that's not an option ;(
$(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>
width(); alert(imageWidth); var imageHeight = Imgsize. height();
Answer: Use the JavaScript clientWidth property You can simply use the JavaScript clientWidth property to get the current width and height of an image. This property will round the value to an integer.
To get the dimensions of image with React, we can get it from the load event handler of the image. We define the onImgLoad function that gets the image from the target property. Then we destructure the offsetHeight and offsetWidth properties from the image. Next, we log the height and width with console.
From the API docs:
In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.
So instead of executing your script in $(document).ready();
use $(window).load();
or better yet, $(image).load();
. For example:
$(document).ready(function() {
var imageContainer = '#image-container';
$(imageContainer).children(':first').children(':first').load(function() {
var imageSrc = $(this).attr('src'); // control test
var imageHeight = $(this).height(); // have also tried attr('height')
alert(imageSrc + ' ' + imageHeight);
});
});
you should wait until your image is loaded - something along the line of
$('#imageContainer').children(':first').children(':first').load(function() {
alert($(this).height());
});
The reason that you can't get the size of the images is that they don't have any size yet. The code runs after the page has loaded but before the images has loaded.
Run the part of the code that needs the image size after all elements in the page are loaded:
$(window).load(function () {
...
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With