Skip to content

Instantly share code, notes, and snippets.

@schmidsi
Created October 10, 2011 18:32
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save schmidsi/1276118 to your computer and use it in GitHub Desktop.
Save schmidsi/1276118 to your computer and use it in GitHub Desktop.
getBgImage: Simple Jquery Plugin to get the dimensions or other attributes from a css background-image
// Inspired by http://stackoverflow.com/questions/5106243/how-do-i-get-background-image-size-in-jquery, a simple jquery plugin who does the task
$.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());
});
@mihawk90
Copy link

I know this is a year old, but I just found it on the StackOverflow question.

I got 2 things that could be done better:

First, in line 5 just use the slice() function as suggested in http://stackoverflow.com/a/12784180
Second: the remove() can't work with the mentioned syntax. It would need to be something like $(tempImg).remove(); as you want to reference an object, not an ID, which you didn't define earlier.

Other than that, thanks for the code, could use it well :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment