Fadein and Fadeout Effect in DIV

Asked

Viewed 2,740 times

1

It may sound cliché, but I haven’t found or been able to adapt any code here on the site to my needs. I apologize if it’s content redundancy, but in the future it might 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:

So it’s working, but without the simple effect of opening.

OBS: I would also like to know if it is possible that when you click the same button, 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';
    } 
  • Is there more than one div you want to open? Each with its own button? Can you put the HTML of that div as well? are elements close to or at different DOM sites?

  • It’s a single DIV, I just want to open it and close it by clicking the button. It all takes place in the same document, the button on top and then the div. NOTE: div has display:None in CSS.

  • Yes. I don’t know if you noticed at the beginning of the question, but it’s been a while since I’ve been trying to adapt the solutions I found and couldn’t. I’d be grateful if you could find a solution now.

1 answer

3


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

You can do it like this:

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

and in CSS defines animation:

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

Example: https://jsfiddle.net/fyf4nsk4/

If you want instead of using fade you can make a slide transition. All with CSS...

  • Almost perfect! I came across a problem: with opacity, the block still occupies space. As I said, the display:One did not take up space, only when it was called.. How to act?

  • @Thiagobarros so I said you can’t use the display: none;. And so use the opacity is better because in addition to allowing transitions you know how it will look on the page. If you want to avoid this behavior you can always use position:absolute; not to have the element as a block. Example -> https://jsfiddle.net/Sergio_fiddle/fyf4nsk4/3/

  • The answer is valid and very useful. Thank you!

Browser other questions tagged

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