How do I get background image size in jQuery?

how to get background image height and width in javascript
jquery get height and width of background image
javascript get the size of an image
how to get height and width of image in js
javascript get image size from url
get the height and width of image
get height of img jquery
resize background image for mobile

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:

jQuery('#myDiv').css('background-image').height();

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.hide();
bgImg.bind('load', function()
{
    var height = $(this).height();
    alert(height);
});
$('#myDiv').append(bgImg);
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.

How do I get background image size in jQuery?, You'll have to do something like this: var url = $('#myDiv').css('background-image'​).replace('url(', '').replace(')', '').replace("'", '').replace('"', ''); var bgImg  I would like my background image to fill the height of the window on which it is being viewed. Obviously I don't know this value since it is variable. I know it is possible to do what I want using jQuery but after searching SO and google for about an hour without finding an answer to my question, I gave up and decided to ask instead.

One more version. No DOM manipulation needed, all characters in image file name supported.

UPDATE See an alternative version below.

var image_url = $('#something').css('background-image'),
    image;

// Remove url() or in case of Chrome url("")
image_url = image_url.match(/^url\("?(.+?)"?\)$/);

if (image_url[1]) {
    image_url = image_url[1];
    image = new Image();

    // just in case it is not already loaded
    $(image).load(function () {
        alert(image.width + 'x' + image.height);
    });

    image.src = image_url;
}

2018 solution

This answer is still receiving upvotes 5 years after. I thought I will share a more complete solution. This builds on top of original code and wraps it into a function. It uses jQuery Deferred Object, adds error handling and updates RegExp to match 3 possible cases: url(), url("") and url(''). It also works on jQuery 1 to 3.

var getBackgroundImageSize = function(el) {
    var imageUrl = $(el).css('background-image').match(/^url\(["']?(.+?)["']?\)$/);
    var dfd = new $.Deferred();

    if (imageUrl) {
        var image = new Image();
        image.onload = dfd.resolve;
        image.onerror = dfd.reject;
        image.src = imageUrl[1];
    } else {
        dfd.reject();
    }

    return dfd.then(function() {
        return { width: this.width, height: this.height };
    });
};

//
// Usage
//
getBackgroundImageSize(jQuery('#mydiv'))
    .then(function(size) {
        console.log('Image size is', size.width, size.height);
    })
    .fail(function() {
        console.log('Could not get size because could not load image');
    });

how to get background-image sizes with jquery?, hi, could someone please tell me how to get the sizes of background-image (​inside a div element) width and height with jquery commands? hi, could someone please tell me how to get the sizes of background-image (inside a div element) width and height with jquery commands?

Late answer, but you could also do this:

var img = new Image;
img.src = $('#myDiv').css('background-image').replace(/url\(|\)$/ig, "");
var bgImgWidth = img.width;
var bgImgHeight = img.height;

Then you don't have to manipulate the dom objects;

Get background image information if element has a one in jQuery , replace('")',''); // Create new Image instance and set path to our background var bg = new Image; bg. src = background; // We now have serveral vars availible to pass through to the plugin // self = the element // background = the url // bg. width = image width // bg. height = image height } }); Can't comment under answers, so here is jQuery version including background-size (posted because this question is first one in google search and may be useful to someone else than me):

Another short way :

function bgSize($el, cb){
    $('<img />')
        .load(function(){ cb(this.width, this.height); })
        .attr('src', $el.css('background-image').match(/^url\("?(.+?)"?\)$/)[1]);
}

usage

bgSize($('#element-with-background'), function(width, height){
    console.log('width : ' + width + ' height : ' + height);
});

https://jsfiddle.net/x4u2ndha/58/

Getting background image width, Hi, Is it possible to get the actual DIV background-image size when background-​size of the DIV is set to cover ? Let say the DIV width is 800px  To set the background image using jQuery, use the jQuery css() method. Example. Use the background-image property to add background image to the web page.

I merged the answer from John together with the Plugin Style from Stryder. This plugin waits for the image to load:

$.fn.getBgImage = function(callback) {
    var height = 0;
    var path = $(this).css('background-image').replace('url', '').replace('(', '').replace(')', '').replace('"', '').replace('"', '');
    var tempImg = $('<img />');
    tempImg.hide(); //hide image
    tempImg.bind('load', callback);
    $('body').append(tempImg); // add to DOM before </body>
    tempImg.attr('src', path);
    $('#tempImg').remove(); //remove from DOM
};


// usage
$("#background").getBgImage(function() {
    console.log($(this).height());
});

feel free to extend this code: https://gist.github.com/1276118

HTML DOM Style backgroundSize Property, Value, Description. auto, Default value. The background-image contains its width and height. length, Sets the width and height of the background image. The first  To change the background image using jQuery, you can use the jQuery CSS() method. For this, the whole property value is specified using the url() functional notation. Approach: Suppose we have an image URL stored in a variable and then use css() method to change the value of background image. Below example illustrates the above approach: Example:

How To: Resizeable Background Image, We can, again, use jQuery and the dimensions plugin to get our browser window's width. Then we'll use that number to set the width attribute on the image​,  The background-size property specifies the size of the background images. There are four different syntaxes you can use with this property: the keyword syntax ("auto", "cover" and "contain"), the one-value syntax (sets the width of the image (height becomes "auto"), the two-value syntax (first value: width of the image, second value: height), and the multiple background syntax (separated with comma).

How to stretch and scale background image using CSS , background-size: auto|length|cover|contain|initial|inherit;. cover: This property value is used to stretch the background-image in x and y direction and cover the​  Hi, Is it possible to get the actual DIV background-image size when background-size of the DIV is set to cover ? Let say the DIV width is 800px and the Getting background image width - jQuery Forum

Set the size of background image using CSS ?, Recommended Posts: CSS | background-image Property · How to change the background image using jQuery ? How to Add Image in Text Background using  That image we will use it to add to our div background image. Basic CSS Structure. Because we will add a background image to an empty container (or with any text inside) you can style the background as you want. I will recommend you to use background-size: cover to stretch the image with 100% width and automatic height.

Comments
  • Is the background fixed? Will it resize with the window, or do you just want to know the image that's bound as the background's information?
  • You will need to load the background image into a img element and check the dimensions of that after it has been loaded
  • No the background image is not fixed. It resizes with the window. The background image is centered and 100x100 px but the surrounding div is 500x500px. How can I get the width 100 and the height 100?
  • it is better to replace all the '"', so you can use: var url = $('#myDiv').css('background-image').replace('url(', '').replace(')', '').replace(/'/g, '').replace(/"/g, '');
  • Hopefully anyone reading these answers reads this comment. This answer is NOT a good practice. Appending the background image to the DOM is a mistake, as is removing it from the #myDiv css. It is easier, faster, and far safer to grab the dimensions in similar manner retrieved here (done better in answers below), and to then use them to change the background-size attribute to your liking.
  • slice is standard, substr isn't; .slice(4, -1) to remove url( ... )
  • No prob :) I believe yours should be the accepted answer. While the others will work the majority of the time, even the most trivial ones can be fragile. I don't see how this could break, nor does it add unneeded complexity.
  • Potential pitfalls: see "Caveats of the load event when used with images" api.jquery.com/load-event
  • I could only get this to work using the imagesLoaded jQuery Plugin.
  • This does not work with an image that scales down (ie, when using background-size: contain;) - it gives the 'native' image properties, but not the ones its being displayed at.
  • Does this specific method create a server request? Or does it pull from memory?
  • @Mike Kormendy, This answer processes the current request. It does not create a new request