Can't get the element height for positioning an element to center by JavaScript

36 Views Asked by At

I am trying to center a span inside a paragraph using JavaScript. This is my code :

document.addEventListener('DOMContentLoaded', () =>  {
    window.onload = function(){middle();}
    var titleHeight = document.getElementById("page-title").clientHeight;
    var titleWidth = document.getElementById("page-title").clientWidth;
    var objHeight = document.getElementById("head-text").clientHeight;
    var objWidth = document.getElementById("head-text").clientHeight;
    var moveit = document.getElementById("head-text");
    var moveit = document.getElementById("head-text");
    function middle(){
        console.log(titleHeight/2-objHeight/2);
        moveit.style.top=titleHeight/2-objHeight/2;
        moveit.style.left=titleWidth/2-objWidth/2);
        }
})

It always returns undefined for the titleHeight.How do I solve this?

I tried centering the element by css but that doesn't help.So I had to switch to JavaScript. I need any possible was by JavaScript to position my element.

2

There are 2 best solutions below

0
Keith On BEST ANSWER

You really should do this with CSS, but in JS you need to call element.getBoundingClientRect() to get accurate positional information.

Also, you're setting objWidth to clientHeight.

It's quite slow and will cause jank, but...

document.addEventListener('DOMContentLoaded', () =>  {
    window.onload = function(){middle();}


    function middle(){
        // This can change, so needs to be in the `middle` function
        const title = document.getElementById("page-title").getBoundingClientRect();
        const titleHeight = title.height;
        const titleWidth = title.width;

        const moveit = document.getElementById("head-text");
        const head = moveit.getBoundingClientRect();
        const objHeight = title.height;
        const objWidth = title.width; // fix typo

        console.log(titleHeight/2-objHeight/2);

        moveit.style.top=(titleHeight/2-objHeight/2)+"px";
        moveit.style.left=(titleWidth/2-objWidth/2)+"px";
    }
})
0
Klas On

Might bee problematic because span is default inline html. Try to set css and define it as inline-block, before the javascript manipulation:

span: { display: inline-block}