Search code examples
javascripthtmlcssfunctiontransition

How to display a div with a smooth transition with Vanilla JavaScript


I have a read more option on my website to display some information.

Currently my button toggles like an on/off switch the display property of the divs.

I want the whole div to appear by smoothly expanding down the page on click of the button, I tried some combinations with transitions but I'm having no luck. I know transitions don't work with the display property, any ideas how to achieve this with preferably just CSS and the one simple function?

function seeMore() {
  const text = document.querySelector('#website-info-idea')
  const text2 = document.querySelector('#website-info-technical ')

  if (text.style.display && text2.style.display === 'block') {
    text.style.display = 'none'
    text2.style.display = 'none'

  } else {
    text.style.display = 'block'
    text2.style.display = 'block'

  }
}
#website-info-idea,
#website-info-technical {
  text-align: center;
  display: none;
  transition: all 1s ease;
}
<a onclick="seeMore()" class="btn btn-secondary btn-md btn-custom">About this Website</a>

<div class="col" id="website-info-idea">Idea</div>
<div class="col" id="website-info-technical">Technical</div>


Solution

  • For the divs to expand smoothly, you have to set a final state height - not "auto" - and the transition must include the change of height.

    Thus:

    function seeMore() {
      const text = document.getElementById('website-info-idea')
      const text2 = document.getElementById('website-info-technical')
      text.classList.toggle("show")
      text2.classList.toggle("show")
    }
    .col {
      opacity: 0;
      height: 0;
      overflow: hidden;
      transition: all 1s ease-in-out;
    }
    
    .col.show {
      opacity: 1;
      height: 23px;
      transition: all 1s ease-in-out;
    }
    <a onclick="seeMore()" class="btn btn-secondary btn-md btn-custom">About this Website</a>
    
    <div class="col" id="website-info-idea">Idea</div>
    <div class="col" id="website-info-technical">Technical</div>