ZUH.
ZUH.

Reputation: 195

Adding transitions to a Javascript Show/Hide Div?

I need help adding transitions to this show/hide js code, the code works for me but I'm struggling with getting these to show/hide smoothly

Any transition will do really, as long as it points me in the direction of getting transitions on both divs that would be perfect

function switchVisible() {
            if (document.getElementById('Div1')) {

                if (document.getElementById('Div1').style.display == 'none') {
                    document.getElementById('Div1').style.display = 'block';
                    document.getElementById('Div2').style.display = 'none';
                }
                else {
                    document.getElementById('Div1').style.display = 'none';
                    document.getElementById('Div2').style.display = 'block';
                }
            }
}
#Div2 {
  display: none;
}
a{cursor: pointer; font-weight: 600;}
<div id="Div1">Div 1</div>
<div id="Div2">Div 2</div>

<a id="Button1" value="Click" onclick="switchVisible();">hide</a>

Upvotes: 0

Views: 1002

Answers (2)

Nguyen Phung
Nguyen Phung

Reputation: 129

Another approach is using visibility: hidden (and visible) combined with transition and optical attribute.

You can check on the following codepen

Upvotes: 2

MstrQKN
MstrQKN

Reputation: 834

When you set display: none you can also add opacity: 0 for the div that is supposed to be hidden.

Then you set opacity: 1 for the div that is supposed to be shown.

Finally, add transition: 0.2s ease-in-out to both of them and you should see a smooth transition when it gets hidden and shown. 0.2s means seconds, so change that to something you like.

EDIT:

So according to Gezzasas comment it won't work with the style attribute. So I've removed that and changed your code so it will show smooth transitions.

You can check the code by clicking here (codepen).

Upvotes: 1

Related Questions