Width defined in css appears as Undefined for Javascript

Asked

Viewed 114 times

0

The problem is this:

1-I created a div and defined its style by its class, in css. Including width.

2- In javascript I try to search to change the value of this width, via "myDiv.style.width", but nothing comes, it seems to be Undefined.

3-My script is written in body, after css.

4-I search for the div element in javascript via mouse function parameter over constant in it:

 <div id="Barra1" class="animacao" onmouseover="increaseBar(this)" 
    onmouseout="decreaseBar(this)" style="background-color: royalblue;">
    </div>

And my css:

<style>
    .animacao {
        border-bottom: 10px;
        border-top: 10px;
        height: 30px;
        width: 10px;
    }

</style>

And the javascript where I’m trying to change width, and it comes Undefined:

<script>
    const initial = 10
    const end = innerWidth
    const step = 5

    function increaseBar(elem){

        const newBegining = elem.style.width+step

       //Nessa console.log abaixo, só aparece o meu texto e nenhum valor do lado 
       console.log("Largura no css: "+elem.style.width)

        if (newBegining < end){
            elem.style.width = newBegining
            setTimeout(() => increaseBar(elem), 1000)
        } 
    }

</script>

NOTE: The div is coming correctly by the parameter. If I give a console.log in the "elem" parameter, the html of my div appears in the console. So that’s not the problem.

Now I have no idea what it is.

2 answers

2


elem.style.width returns the width set by javascript.

ex:

function increaseBar(elem){

   elem.style.width = '150px';

   // já aparece 150px
   console.log("Largura no css: "+elem.style.width)
}

Can use:

  • clientWidth is the interior of the element, includes padding but excludes edges and scrollbar
  • offsetWidth includes padding edges and scrollbar
  • So, to get the width of the div I use elem.clientWidth or elem.offsetWidth. But to change the div, I keep assigning the new value to elem.style.width?

1

Use "offsetWidth" to access the value that is in CSS style:

** note for the ";" in the code and the concatenation of "px" in:

elem.style.width = newBegining + 'px';

const initial = 10;
const end = innerWidth;
const step = 5;

function increaseBar(elem){
    const newBegining = elem.offsetWidth + step;

   //Nessa console.log abaixo, só aparece o meu texto e nenhum valor do lado 
   console.log("Largura no css: "+ newBegining);

    if (newBegining < end){
        elem.style.width = newBegining + 'px';

    } 
}
    .animacao {
        border-bottom: 10px;
        border-top: 10px;
        height: 30px;
        width: 10px;
        background-color: royalblue;
    }
<div id="Barra1" class="animacao" onmouseover="increaseBar(this)"></div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.