1

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!

crashtest
  • 89
  • 2
  • 8

2 Answers2

1

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

finalfreq
  • 6,830
  • 2
  • 27
  • 28
0

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>
Mehrad
  • 1,495
  • 14
  • 22
  • Thank you, this looks promising, but can it be done with `display:none` aswell? `visibility:hidden` leaves space even if the menu is supposed to be collapsed. – crashtest Sep 09 '16 at 21:50
  • set the height to 0 as well I updated my answer to reflect that. – Mehrad Sep 09 '16 at 22:03
  • The transitions work for visibility and opacity, but height gets instantly reduced to 0 without transition?! Any idea what could cause this? – crashtest Sep 10 '16 at 15:01
  • the problem is javascript is setting the height to 0 before the css transition finishes, take a look at this answer http://stackoverflow.com/a/15618028 – Mehrad Sep 10 '16 at 15:12