views:

67

answers:

3

Is it possible to use JavaScript to get the actual size (width and height in pixels) of a CSS referenced background image?

A: 

Not sure about plain javascript, however, you can use something like jQuery to give you the computed width and height of the image(s) using the width() and height() methods.

Sarfraz
+3  A: 

Yes, and I'd do it like this...

  window.onload = function() {

    var imageSrc = document
                    .getElementById('hello')
                     .style
                      .backgroundImage
                       .replace(/"/g, '')
                       .replace(/url\(|\)$/ig, '');
    // I just broke it up on newlines for readability        

    var image = new Image();
    image.src = imageSrc;

    var width = image.width,
        height = image.height;

    alert('width =' + width + ', height = ' + height)    

}

Live on JSbin.

Some notes...

  • We need to remove the url() part that JavaScript returns to get the proper image source.
  • We make a new Image object and set its src to the new image.
  • We can then read the width & height.
  • This method also has the advantage that we are not creating temporary DOM elements.

jQuery would probably a lot less of a headache to get going.

alex
+1  A: 

Here it is in jQuery:

var actualImage = new Image();
actualImage.src = $('YOUR SELECTOR HERE').css('background-image').replace(/"/g,"").replace(/url\(|\)$/ig, "");

actualImage.width // The actual image width
actualImage.height // The actual image height

Thanks for the sweet regex alex.

Kirk