7

I have a hidden div #about. By clicking the link #clickme the div gets unhidden by a function. Unfortunately the CSS transition (opacity) is not working though it should keep both classes .hide and .unhide including the transitions. Any ideas?

HTML

<li><a id="clickme" href="javascript:unhide('about');">click me</a></li>

<div id="about" class="hide">
<p>lorem ipsum …</p>
</div>

CSS

.hide { 
display: none;
-webkit-transition: opacity 3s;
-moz-transition: opacity 3s;
-o-transition: opacity 3s;
transition: opacity 3s;
opacity:0;  
}   
.unhide { 
display: inline;
opacity:1;
}

SCRIPT

<script>
function unhide(divID) {
var element = document.getElementById(divID);
if (element) {
  element.className=(element.className=='hide')?'hide unhide':'hide';
}
}
</script>
  • I think the reason for why it doesn't work is because you can't transition an object from display: none; to display: inline or block etc ... – Christofer Vilander May 23 '14 at 06:36
  • try putting `!important` in class unhide's properties. but display property won't work with transition so use width or height instead of that. – Brijesh Gajjar May 24 '14 at 16:10

1 Answers1

3

You need to remove the display:none from the element. You're essentially hiding the element 2 ways - display:none and opacity:0.

If you remove the display:none and only transition the opacity property the effect will work.

CSS

.hide { 
    -webkit-transition: opacity 3s;
    -moz-transition: opacity 3s;
    -o-transition: opacity 3s;
    transition: opacity 3s;
    opacity:0;  
}   

.unhide { 
    opacity:1;
}

function unhide(divID) {
  var element = document.getElementById(divID);
  if (element) {
    element.className = (element.className == 'hide') ? 'hide unhide' : 'hide';
  }
}
.hide {
  -webkit-transition: opacity 3s;
  -moz-transition: opacity 3s;
  -o-transition: opacity 3s;
  transition: opacity 3s;
  opacity: 0;
}

.unhide {
  opacity: 1;
}
<li><a id="clickme" href="javascript:unhide('about');">click me</a></li>

<div id="about" class="hide">
  <p>lorem ipsum …</p>
</div>

Here is a jsFiddle showing it action.

Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184
  • to making the transition happen the `hide` class shoud still be attach to the classname right? my animation didn't work when i changing `hide` to `unhide` – Irvan Hilmi Jun 01 '22 at 07:07