CSS fading through does not work properly

I am trying to animate use a page element using the CSS transition on opacity property. Attenuation works correctly, but Fading in does not. What am I doing wrong?

Some facts are really strange :

  • Without using the .no-display class, everything works as expected (but I have to use it).
  • Playback commands in the browser console work fine (but the function does not work).

Code:

HTML

 <p><a href="javascript:fadeIn()">Fade in</a></p> <p><a href="javascript:fadeOut()">Fade out</a></p> <div class="no-display invisible" id="square"></div> 

CSS

 .no-display { display: none; } .invisible { opacity: 0; } #square { width: 500px; height: 500px; background-color: red; border: 1px solid black; -webkit-transition: opacity 2s ease; -moz-transition: opacity 2s ease; -ms-transition: opacity 2s ease; -o-transition: opacity 2s ease; transition: opacity 2s ease; } 

Javascript

 function fadeIn() { square.classList.remove("no-display"); square.classList.remove("invisible"); } function fadeOut() { square.classList.add("invisible"); setTimeout(function() { square.classList.add("no-display"); }, 2000 ); } 

Or: http://jsfiddle.net/V2Sar/6/ .

Note. I can not use any frameworks like jQuery. I should only work with pure JavaScript.

+4
source share
2 answers

An easy way to trigger CSS transitions with JS is to switch class names, and an easy way to do this is through the classList API .

Js

 var square = document.getElementById("square"); function fadeIn() { square.classList.remove("invisible"); } function fadeOut() { square.classList.add("invisible"); } 

CSS

 #square { opacity: 1; transition: opacity 2s ease; } #square.invisible { opacity: 0; } 

http://jsfiddle.net/V2Sar/5/

Also, make sure your scripts are at the end of the <body> , so you don't have to worry about whether the DOM is constructed (a separate parameter in jsfiddle for this).

Browser support is small (no support in IE9), but there is a pad at https://github.com/eligrey/classList.js

Let me know if this is not enough for you, and I will also post some alternatives.

+2
source

The only problem is "display: none;". Just replace it with "visibility: hidden."

The reason is that display: none does not create the final element in the DOM. As such, it cannot disappear into that which does not exist. When it is created, it is created in a visible way.

However, 'visibility: hidden' creates the resulting element in the DOM, just does not show it. Since it exists, it can disappear if necessary.

0
source

Source: https://habr.com/ru/post/1488650/


All Articles