FadeIn and FadeOut effect in DIV

1

It may seem cliché, but I did not find and could not adapt any code here from the site to my needs. I apologize if it is content redundancy, but in the future it may help other people.

How can I be adding a FadeIn and FadeOut effect when opening and closing the element, based on the following javascript script:

The following is working, but not just the effect of opening.

NOTE: I would also like to know if it is possible to click the same button to close the DIV with a FadeOut.

HTML :

 <button type="button onclick="Mudarestado('formulario')">Abrir div</button>

Javascript:

   function Mudarestado(el) {
        var display = document.getElementById(el).style.display;

        if(display == "none")
            document.getElementById(el).style.display = 'block';
        else
            document.getElementById(el).style.display = 'none';
    } 
    
asked by anonymous 18.12.2015 / 20:27

1 answer

2

To have an effect of fade you can not have display: none; because CSS does not transition from display . I suggest you do this with a CSS class, where you change opacity and choose the speed of the animation.

You can do this:

function Mudarestado(el) {
    document.getElementById(el).classList.toggle('mostrar');
}

and in CSS you define the animation:

#formulario {
    opacity: 0;
    transition: opacity .5s;
}
#formulario.mostrar {
    opacity: 1;
}

Example: link

If you want instead of using fade you can do a transition with slide . Everything with CSS ...

    
18.12.2015 / 20:47