Foad Foad - 5 months ago 80
CSS Question

How do I get background image size in jQuery?

The problem is simple. How do I get a div's background image size (width and height) in jQuery. Is it even possible? I thought this would work:


The error message I get is that this is not a function.


You'll have to do something like this:

var url = $('#myDiv').css('background-image').replace('url(', '').replace(')', '').replace("'", '').replace('"', '');
var bgImg = $('<img />');
bgImg.bind('load', function()
    var height = $(this).height();
bgImg.attr('src', url);

Due to the simplicity of the code, you cannot use parenthesis or quotation marks in the URLs of your background images. However, the code could be extended for greater support. I just wanted to convey the general idea.