I need to get the width & height of a CSS background image and inject it into document.ready javascript. Something like:
$(document).ready(function(){
img = new Image();
img.src = "images/tester.jpg";
$('body').css('background', 'url(' + img.src + ')');
$('body').css('background-size', img.width + 'px' + img.height + 'px');
});
The problem is, the image width and height aren’t loaded in at the time of document.ready, so the values are blank. (They’re accessible from console, but not before).
img.onload = function() { ... } retrieves the width and height, but DOM $(element) calls aren’t accessible from within img.onload.
In short, I’m a little rusty on my javascript, and can’t figure out how to sync image params into the DOM. Any help appreciated
EDIT: jQuery version is 1.4.4, cannot be updated.
You could use
$.holdReady()to prevent jQuery’sreadymethod from firing until all of your images have loaded. At that point, their width’s and height’s would be immediately available.Star by calling
$.holdReady(true). Within theonloadmethod of each image, check to see how many images have been loaded all together, and if that matches the number of expected images, you can$.holdReady(false)to fire the ready event.If you don’t have access to
$.holdReady(), you could simply wait to spit out your HTML until all of the images have loaded by still calling a function: