Help us understand the problem. What is going on with this article?

javascript で fadeOut() したい

More than 3 years have passed since last update.

opacityだけじゃなく、display:noneにもしたいのだ。
jQueryだとものすごく簡単にできるが、jQueryが使用できない場面とか、ふとjQueryじゃなくjsだけで書いてみようかな気持ちのときに。

まずはjQueryのfadeOut

これだけで、ふわっと消えるってほんと便利ですよね。

inedx.html
<p id="text">This is a pen.</p>
app.js
$('#text').click(function() {
  $('#text').fadeOut();
});

JavaScript + CSS3

ふわっとの部分をCSS3で実現。
クリック時にクラスをつけcssでopacityを、display:noneはjs側で。

inedx.html
<p id="text">This is a pen.</p>
style.css
.fadeout {
  animation : fadeOut 1s;
  animation-fill-mode: both;
}
@keyframes fadeOut {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
app.js
var text = document.getElementById('text');
text.addEventListener('click', function(){
  text.classList.add('fadeout');
  setTimeout(function(){ 
    text.style.display = "none"; 
  }, 1000);
}, false);

サンプルはこちら(CodePen)
https://codepen.io/snjssk/pen/EgRGGp

snjssk
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away