0

I need to get the height of an image on the page and try to do so only after the image has been loaded. However, it seems like I'm still getting a height of 0 for some of the images on the page. Here's my code:

   carousel_img.on('load', function(){
         setCarouselImageMargins(carousel_img, carousel_width);
   });

   function setCarouselImageMargins(image, width){
         var carousel_left_margin = (image.width()-parseInt(width))/2*-1;
         image.css('margin-left', carousel_left_margin);
         console.log('carousel image width: ' + image.width()); // this is returning 0
         console.log('carousel_left_margin: ' + carousel_left_margin);
   }

Is there another way to ensure the image is fully loaded on the page?

scientiffic
  • 9,045
  • 18
  • 76
  • 149
  • How are you adding the images? – Diodeus - James MacFarlane Jul 16 '14 at 19:20
  • They're being added to the page using jquery and ruby. I would share the code, but it's messy... – scientiffic Jul 16 '14 at 19:22
  • load doesn't work reliably for images that are cached and is therefore discouraged. See http://api.jquery.com/load-event/ A common challenge developers attempt to solve using the `.load()` shortcut is to execute a function when an image have completely loaded. **There are several known caveats with this that should be noted**. These are: It doesn't work consistently nor reliably cross-browser, It doesn't fire correctly in WebKit if the image src is set to the same src as before, It doesn't correctly bubble up the DOM tree, Can cease to fire for images that already live in the browser's cache. – Ruan Mendes Jul 16 '14 at 19:22
  • thanks for your response. I read through the challenges but don't see possible solutions on the page...any suggestions? – scientiffic Jul 16 '14 at 19:24
  • For a workaround, do `$("img").one("load", function() { // do stuff }).each(function() { if(this.complete) $(this).load(); See http://stackoverflow.com/questions/3877027/jquery-callback-on-image-load-even-when-the-image-is-cached });` – Ruan Mendes Jul 16 '14 at 19:24

2 Answers2

0

you can do it after

   $( document ).ready(function() {
      setCarouselImageMargins(carousel_img, carousel_width);
   });
Andy
  • 49,085
  • 60
  • 166
  • 233
0

You can use clientWidth and clientHeight DOM properties to get the inner dimension of a DOM element in your case image. So in your scenario, it will get the actual dimension of the visible image

    var image = document.getElementById('imageid'); 
    //or however you get a handle to the IMAGE
    var width = image.clientWidth;
    var height = image.clientHeight;