How do I increase a CSS property using Js?

Asked

Viewed 45 times

1

I’m needing that every time I press a button, a CSS property increases by 10, example:

<style>div { left: 0; }</style>
<button>Aumentar left em 10</button>
<div></div>

And every time I click, it increases Div’s left by 10.

2 answers

0

You can create a variable to keep information of how many pixels the element should be away (by property left) and, with each click on the button, change this property and compute the new left using the property style.

Something like that:

const btn = document.querySelector('button');
const div = document.querySelector('#target');

let currentLeft = 0;
btn.addEventListener('click', () => {
  currentLeft += 10;
  
  // Após adicionar 10 à nossa variável, adicionamos no estilo do elemento:
  div.style.left = `${currentLeft}px`;
});
#target {
  left: 0;
  
  position: relative;
  width: 50px;
  height: 50px;
  background-color: orangered;
}
<div id="target"></div>

<button>Clique!</button>

0

You can use the offsetLeft to take the value of left if not yet defined.

offsetLeft returns the computed value of left, for example:

Element x is in position left 200px. offsetLeft had returned 200.

The problem is that offsetLeft just returns values, it cannot be set. To make an element move we will have to mess with its style, example: elemento.style.left

(Remembering that to move an element using left, top, right or bottom this element must have the CSS property position, has several possible values, but I will demonstrate with the value relative. Link to learn more about the different values of position: The property position)

function mover(elemento) {
  elemento.style.left = elemento.offsetLeft + 10 + "px";
}

/*
Ou no estilo de função em uma variavel:

mover = function(elemento) {
  elemento.style.left = elemento.offsetLeft + 10 + "px";
}


Ou uma função de seta:

var mover = (elemento) => {
  elemento.style.left = elemento.offsetLeft + 10 + "px";
}
*/
body {
  /* PARA ENFEITAR > plano de fundo ciano */
  background: cyan;   
}
button {
  position: relative;
  
  /* PARA ENFEITAR > transição de 1 segundos */
  transition: 1s;
}
<!-- O "this" de "mover(this)" se refere ao elemento do proprio botão -->
<button onclick="mover(this)">Clica aqui para me mover!</button>

Browser other questions tagged

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