Using jQuery each to grab image height

30,500

Solution 1

Use this:

imageWidth = $(this).children("img").attr("width")

The following selects all your images:

$(".thumb img")

... so when you ask for the attribute it returns it from the first object in the collection

Sorry for all the edits... but it is best to reuse jquery objects, so:

var $this = $(this)

Then refer to $this were needed for optimization. Not that big a deal in this example, but it is a good practice to use.

Solution 2

You won't be able to use document.ready() to do this as the images will not have loaded by the time that is called.

You actually need to put this code into the onload() event handler, which is called after the document and all images have finished loading.

It is only when the images have finished loading that the browser knows how big they are.

Share:
30,500
Admin
Author by

Admin

Updated on March 08, 2020

Comments

  • Admin
    Admin about 4 years

    I have a bunch of images on a page. I'm trying to use jQuery to grab the height of each image and display it after the image. So here is my code:


    
    $(document).ready(function() {
      $(".thumb").each(function() {
        imageWidth = $(".thumb img").attr("width");
        $(this).after(imageWidth);
      });
    });

    <div class="thumb"><img src="" border="0" class="thumb_img"></div>
    <div class="thumb"><img src="" border="0" class="thumb_img"></div>
    <div class="thumb"><img src="" border="0" class="thumb_img"></div>
    

    [...]


    My logic behind the jQuery is that I want to go through each "thumb" selector, assign the height of the img inside "thumb" to the variable "imageWidth", and then display the height in text after each "thumb".

    The problem I'm having is that it's only working on the first image and then quitting. I can get it to work if I use the "thumb_img" class, of course, but I need access to the height of the image for the "thumb" class.

    Hopefully this isn't too confusing as I'm fairly new to jQuery. Thanks advance.

  • MitMaro
    MitMaro over 14 years
    You beat me to the answer. +1
  • mothmonsterman
    mothmonsterman over 14 years
    sorry buddy, it does seem like a race sometimes
  • mhenry1384
    mhenry1384 almost 13 years
    According to the jQuery docs, the load event is not reliable when used on images: api.jquery.com/load-event
  • Plasma
    Plasma about 11 years
    Thanks, this solved my issue! I had to use $(window).load(function()); instead of $(document).ready(function());