0

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>

1
  • Is using display necessary? Can we use visibility instead? Commented Jun 29, 2018 at 10:35

2 Answers 2

2

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

You can check on the following codepen

Sign up to request clarification or add additional context in comments.

Comments

1

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).

6 Comments

This will not work. display: none; will always instantly show and hide because it is either displaying or not.
why don't you go for jquery ?
Any way you could put this in could perhaps @AdeshKumar
@ZUH. I've updated my answer to show how it would work with my solution. No jQuery needed.
When going the simple route of just changing opacity, you might also want to set user-select:none;pointer-events:none; when opacity is 0
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.