Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS transition not working when changing class by javascript

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>
like image 531
user3656519 Avatar asked May 20 '14 12:05

user3656519


1 Answers

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.

like image 130
Brett DeWoody Avatar answered Oct 21 '22 05:10

Brett DeWoody