0

is possible to get background image width which is defined in CSS?

body {
    background-image: url('background.jpg');
}

I need something like this:

window.getComputedStyle(document.body, 'background-width');
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
Václav Dajbych
  • 2,584
  • 2
  • 30
  • 45

3 Answers3

1

is possible to get background image width which is defined in CSS?

I don't think so, but you should be able to use a little trick : Load the image into an img element as described in this question.

If you do this after the document has been fully loaded, the browser should fetch the image from the cache.

Community
  • 1
  • 1
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
1
var u = window.getComputedStyle(document.body, 'background-image');
u = u.replace(/url\(/, '').replace(/\)/, '');
var w = 0;
var i = new Image();
i.onload = function( ){ w = this.width; alert(w); }
i.src = u;

warning: i have ommitted a case, when body has no background image specified, keep that in mind.

c69
  • 19,951
  • 7
  • 52
  • 82
0

It's impossible to do this directly without some sort of work around.

  1. Use JQuery to detect what image the background has, with the imagesLoaded (recommended) or onImagesLoad plugin.
  2. Use the JQuery Dimensions plugin to get the image size.
desbest
  • 4,746
  • 11
  • 51
  • 84