Get CSS attribute in JS

4

I want to get a property of css in js to add its value.

In the following code I have a div called bubble, and what I want is to increase its value in scale (0.1) each time the function is executed and the only way I can think of is to obtain the value of the scale () attribute and add the 0.1

I think there are other solutions but I can not think of it

function bubblestart(){
  document.getElementById("bubble").style.transform = "scale(1.5)";
}
<div class="button" onclick="bubblestart()">Start</div>
 <div id="bubble"></div>
    
asked by Tefef 10.10.2018 в 11:54
source

2 answers

3

If what you really want is just add 0.1 (is 0.1 pixel or do you want to scale it 10%?). I interpret it as you want to add 0.1. So do not use scale, because scale () scales it multiplying and the bigger, the more it grows.

You can use this solution:

var bubble = document.getElementById('bubble');

bubble.addEventListener('click', () => {
  var ancho = bubble.getBoundingClientRect().width,
      alto = bubble.getBoundingClientRect().height,
      escalarAncho = ancho + 0.1 + 'px',
      escalarAlto = alto + 0.1 + 'px';
      bubble.style.width = escalarAncho;
      bubble.style.height = escalarAlto;
      console.log(ancho + ' ' + alto +' dimensiones');
});
.bubble {
      position: relative;
      margin: 0 auto;
      transition: all .3s ease-out;
      width: 50px;
      height: 50px;
      background-color: red;
      border: 1px solid red;
      border-radius: 50%;
  cursor: pointer;
      }
<div id="bubble" class="bubble"></div>

You can play with the values to make it grow. You can multiply by 0.1 to grow 10%. Now, if what you really want is to use scale then, use this other solution

var bubble = document.getElementById('bubble');

bubble.addEventListener('click', () => {
  var ancho = bubble.getBoundingClientRect().width,
      escalar = 'scale(' + ancho * 0.1 + ')';
      bubble.style.transform = escalar;
      console.log(ancho + ' es el ancho ahora');
});
.bubble {
      position: relative;
      margin: 0 auto;
      transition: all .3s ease-out;
      width: 50px;
      height: 50px;
      background-color: red;
      border: 1px solid red;
      border-radius: 50%;
  cursor: pointer;
      }
<div id="bubble" class="bubble"></div>

Good luck!

    
answered by 10.10.2018 / 23:19
source
4

One way could be:

<div class="button" onclick="bubblestart()">Start</div>
<div id="bubble" data-scale="0.1"></div>

You define an attribute with a default value. Then your javascript reads that attribute, increments it and saves it in the attribute. You also modify the scale as you need with this value:

function bubblestart(){
  bubble = document.getElementById("bubble");
  bubbleScale = +(bubble.getAttribute("scale")) + 0.1;
  bubble.style.transform = "scale("+bubbleScale+")";
  bubble.setAttribute("data-scale", bubbleScale);
}

It is an approximation, check it to adapt it to your need.

    
answered by 10.10.2018 в 12:37