Kirk Ouimet Kirk Ouimet - 4 years ago 142
CSS Question

Get the Size of a CSS Background Image Using JavaScript?

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

Answer Source

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

  window.onload = function() {

    var imageSrc = document
                       .replace(/url\((['"])?(.*?)\1\)/gi, '$2')

    // 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)    


Some notes...

  • We need to remove the url() part that JavaScript returns to get the proper image source. We need to split on , in case the element has multiple background images.
  • We make a new Image object and set its src to the new image.
  • We can then read the width & height.

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download