'JavaScript - safari returns wrong width values

I have built a small gallery which automatically adjusts to the size of the window but the script obviously needs the correct window size to calculate the image sizes.

Theoretically it is easy to get the width with .offsetWidth, .scrollWidth , .clientWidth or window.innerWidth but for some reason Safari returns the wrong width every time. Under Firefox it runs without problems. According to W3Schools all these functions work in all browser types.

I know this question came up before: Safari is returning the wrong width value but there was no solution back then.

My Script: (maybe I have made a mistake)

const body = document.querySelector('body')
const row = body.offsetWidth //one row is has the width of the parent elemenet (body)
const item = document.getElementsByClassName('gallery-item')

  window.onload = function () {
    let columnAmount = 3                           //amount of columns the gallery have
    let imgMargin = 1.5                            //half the gap size between images

    let gaps = columnAmount + 1                    //how many gaps are in a row
    let imgRowSpace = row - (imgMargin * 2 * gaps) //how many space is left for images
    let imgSize = imgRowSpace / columnAmount       //how large is one image

    for(var i = 0; i < item.length; i++) {         //change the properties

      item[i].style.height = imgSize + 'px'
      item[i].style.width = imgSize + 'px'
      item[i].style.margin = imgMargin + 'px'

    }  

    body.setAttribute('style', 'padding: ' + imgMargin + 'px')

  }

I hope someone of you has more knowledge than me.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source