To place the ball in the middle of the field element, I need to divide its size by 2, but I cannot divide its size by two, because for some reason it is impossible to get its width and height in any way. How are the pictures of the element in the example below correctly getting offsetWidth / Height?

let ball = document.getElementById('ball'); let field = document.getElementById('field') console.log(ball.offsetWidth); -> ВЫВОДИТ 0 почему-то ball.style.left = document.body.children[0].clientWidth / 2 + "px" 

full example

 let ball = document.getElementById('ball'); let field = document.getElementById('field') console.log(ball.offsetWidth); ball.style.left = document.body.children[0].clientWidth / 2 + "px" 
 #field { width: 200px; border: 10px groove black; background-color: #00FF00; position: relative; } #ball { position: absolute; } 
 <div id="field"> <img src="https://js.cx/clipart/ball.svg" id="ball"> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . </div> 

http://plnkr.co/edit/9UdA9ZJJYBiss5vjTBB2?p=preview

    1 answer 1

    We need to do this after rendering everything.

    onload - The event on the window triggered when the entire page is loaded, including the resources on it - styles, images, frames, etc.

    And also, in order to center the ball, taking into account the fact that the coordinate 0,0 is in the upper right corner, then in addition to half the field width, the ball must also be shifted half its width to the left.

     window.onload = function() { let ball = document.getElementById('ball'); let field = document.getElementById('field') console.log('ball width: ' + ball.clientWidth + ', field width: ' + field.clientWidth); ball.style.left = (field.clientWidth / 2) - (ball.clientWidth / 2) + "px" } 
     #field { width: 200px; border: 10px groove black; background-color: #00FF00; position: relative; } #ball { position: absolute; } 
     <div id="field"> <img src="https://js.cx/clipart/ball.svg" id="ball"> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . </div> 

    • Thank you, actually I wanted to do this, for this I actually needed to know the ball's metric, otherwise why would I create a theme?) I write again: To place the ball in the middle of the field element, I need to divide its size 2. For .onload thanks, that's all I wanted to know. - Anton
    • @Anton well, you never know ¯ \ _ (ツ) _ / ¯ - Aleksey Shimansky