CSS Change Time with JavaScript

3

I have a function:

function togglePopup1() {
    document.getElementById('desktop-card').style.width = '480px';
}

The code is for width of the page to increase with a click.

But how do I make this change happen, for example, in 2 seconds? I've looked everywhere and have not figured out how to enter a runtime.

In addition to width , there are several other CSS properties that also change at the same time.

    
asked by anonymous 16.11.2018 / 08:28

3 answers

7

I'm not very good at javascript but the solution is simple and to be done with CSS using transition .

function togglePopup1() {
    document.getElementById('desktop-card').style.width = '480px';
}
#desktop-card {
  width: 100px; /* tamanho inicial */
  height: 50px; 
  background: #ddd; /* Cor para demonstrar o efeito  */
  transition: 2s; /* Class transition */
  -moz-transition: 2s; /* Firefox 4 */
  -webkit-transition: 2s; /* Safari and Chrome */
  -o-transition: 2s; /* Opera */
}
<button onclick="togglePopup1()">Start</button>
<div id="desktop-card"><div>
    
16.11.2018 / 11:07
5

Assuming you have the style class ready for desktop-card , you only have to add the transition properties in that class and when you change the style in JS it will receive the transition according to what you set up:

function togglePopup1() {
    document.getElementById('desktop-card').style.width = '480px';
}
#desktop-card{
  background-color: black;
  color: white;
  width: 100px;
  transition-delay: 2s;
  transition-duration: 2s;
}
<button onclick="togglePopup1()">Aperte Aqui</button>

<div id="desktop-card">Teste</div>

Note: I have used two properties transition , transition-delay which specifies the time for the animation to start and the transition-duration that specifies the animation duration time.

There are other properties you can use. Here you can read and see more examples.

    
16.11.2018 / 11:09
0

Vitor, vllw mano.

I got it here, in the early morning I was so sleepy I did not even remember what I could use with CSS.

However, it did not work for example

document.getElementById('desktop-card').style.display = 'block';

In case the Div # desktop-card appears smooth too.

    
16.11.2018 / 18:29