Razvan Razvan - 5 months ago 35
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");
var imageSrc = $(this).data('image-src');
imageSrc.replace(/url\((['"])?(.*?)\1\)/gi, '$2')
var image = new Image();
image.src = imageSrc;
var width = image.width,
height = image.height,
ratio = width/height;
if (ratio < 1) {
$(this).css('background-size', 'contain');

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


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



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