crashtest
crashtest

Reputation: 99

Adding transition to show-hide menu

I have a fairly simple menu that works as intended, but I just don't know how to add a transition to it so it will look smoother. Here is what I have:

<script type="text/javascript">
function showhide(id) {
    var e = document.getElementById(id);
    e.style.display = (e.style.display == 'block') ? 'none' : 'block';
    e.style.transition = "all 1s";
 }
</script>


<a href="javascript:showhide('SERIES')">
    <div class="search-menu-maincategory">
        Maincategory to click on
    </div>
</a>

<div id="SERIES">
    <div class="search-menu-subcategory">
        One of the subcategories to show and hide
    </div>
</div>

Obviously the e.style.transition = "all 1s"; part is not what I need since it is not working. How can I add a one second transition between the show and hide? Thanks!

Upvotes: 2

Views: 2959

Answers (2)

Mehrad
Mehrad

Reputation: 1543

Setting the height: 0 should fix your block problem

function showhide(id) {
    var e = document.getElementById(id);
    e.classList.toggle("m-fadeOut");
 }
.m-fadeOut {
  visibility: hidden;
  opacity: 0;
  height: 0;
  transition: visibility 0s linear 300ms, opacity 300ms, height 300ms;
}
<a href="javascript:showhide('SERIES')">
    <div class="search-menu-maincategory">
        Maincategory to click on
    </div>
</a>

<div id="SERIES">
    <div class="search-menu-subcategory">
        One of the subcategories to show and hide
    </div>
</div>

Upvotes: 0

finalfreq
finalfreq

Reputation: 6980

Two things: you can't transition on a display property, use visibility and opacity instead.

#foo { transition-property: visibility, opacity; transition-duration: 0, 1s; }

#foo.hidden { opacity: 0; visibility: hidden; transition-property: opacity, visibility; transition-duration: 1s, 0; transition-delay: 0, 1s; }

I suggest using css class names to control showing/hiding otherwise you will have to write a function that uses the request animation frame function to redraw the window so the animation actually shows up otherwise you wont have a transition https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame

Upvotes: 1

Related Questions