Razvan Razvan - 2 months ago 7
jQuery Question

Get background image's aspect ratio in jQuery

The client has a WordPress based website using the Theme Hiker. On this page, there is a gallery that, instead of inline images, uses background images.

I need to determine the value of those images with over height ratio. If the ratio is smaller than 1, add

background-size: contain
to each slide (a list element) that meets that condition.

I made this function:

function setBackgroundSize() {
var $sliderItem = $(".full-photos li");
$sliderItem.each(function(){
var imageSrc = $(this).data('image-src');
imageSrc.replace(/url\((['"])?(.*?)\1\)/gi, '$2')
.split(',')[0];
var image = new Image();
image.src = imageSrc;
var width = image.width,
height = image.height,
ratio = width/height;
console.log(ratio);
if (ratio < 1) {
$(this).css('background-size', 'contain');
}
});
}
$(window).load(setBackgroundSize());


The problem is that it only works after the page has loaded, I refresh it. What's wrong with the script? Thx!

Answer

$(window).load(setBackgroundSize()); is executing the setBackgroundSize function immediately (before the load event occurs). Pass a reference to the function instead:

$(window).load(setBackgroundSize);

or

$(window).load(function() { setBackgroundSize(); });