Marcin Doliwa Marcin Doliwa - 4 months ago 11
jQuery Question

Array of widths changes on refresh

I'd like to have array

slide_widths
with widths of all
.slide
elements:

$( document ).ready(function() {
var $slider = $('.slider ul');
var slider_width = $slider.width();
var $slides = $('.slide');
var slide_widths = $.map($slides, function(slide) {
return slide.getBoundingClientRect().width;
});

console.log(slide_widths);
});


I get different results when I refresh my page:

1. [201.328125, 180, 214.28125, 180, 180, 180, 168.46875, 180, 145.078125, 144, 142.1875, 250.6875, 0, 0, 0, 0, 0, 0, 0, 0]

2. [201.328125, 180, 214.28125, 180, 180, 180, 168.46875, 180, 145.078125, 144, 142.1875, 250.6875, 155.515625, 180, 180, 176.03125, 0, 0, 0, 0]


I guess this
map
function is still working when
console.log
outoputs an array? How can I avoid it ?

Answer

It would seem that your function is grabbing the element widths before they're actually loaded, and so the not-yet-loaded elements are returning widths of 0.

Try using $(window).on("load", function() { instead of $(document).ready(function() {

$(window).on("load" will wait for all elements on the page to load, whereas $(document).ready will not.