Trigger a CSS transition after showing a hidden element in CSS

Normally, a CSS transition won't occur if you are trying to apply it to an element which was hidden and now should be visible. Here's how to fix it.

TAGS: javascript,jquery,css transitions

01/06/2016

I’ve been running into this issue for years and finally found an easy hack to fix it. The probem: You have an element that is hidden by default with CSS. You want to show it when you click a button or something, but have it fade in with a css transition (vs javascript). So you set the following CSS:


.element { //disabled
  opacity: 0
  display: none;
  transition: opacity .2s linear
}

.element.active { //visible
  opacity: 1
}
            

So, then you have your javascript action which shows the element:

But strangely this method also involves automatically playing your video, muting your video, and looping your video. To get everything but the play button back to normal, do this:


$('.button').on('click',function(){
  $('.element').show().addClass('active');
});
            

But for some reason, it does not animate - it goes right to its visible state without the animated fade. Why? Not sure. How to fix it? Easy. Just add one command to the chain:

$('.element').show().focus().addClass('active'); 

Here's a demo: