PrimRock
PrimRock

Reputation: 1156

Fading in HTML text in JavaScript

I've been trying to get some text to fade in from opacity 0 to 100, but I can't seem to get it to work right. Credits to the person for the original fadeOut version.

Here's the code...

fadeIn = function(id, speed) {
    var s = document.getElementById(id).style;
    s.opacity = 0;
    (function fade() {(s.opacity+= .1)<100?s.display="inline":setTimeout(fade,speed)})();
}

Upvotes: 2

Views: 98

Answers (2)

nixkuroi
nixkuroi

Reputation: 2269

All you have to do is set an interval and then count up to 100 by your speed/100 in increments.

function fadeIn(id, speed) {
  var max = 100, count = 0;
  var increment = speed / max;       
    
  var obj = document.getElementById(id);
  var interval = setInterval(function() {
    obj.style.opacity = (count / max);
    if (count == max) {
      clearInterval(interval);
    }
    count++;
  }, increment);
}
#faded {
  opacity: 0;
}
<div id="faded">Fade me in</div>
<button onclick="fadeIn('faded', 3000)">Fade it in</button>

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

I think there are 2 problems, 1 the opacity values vary from 0...1 not 0..100 also when opacity is 1 you need to stop the loop.

Second, s.opacity returns a string, so since you are using + operator you need to convert the value to a string else a string concatenation will be performed

fadeIn = function(id, speed) {
  var s = document.getElementById(id).style;
  s.opacity = 0;
  (function fade() {
    (s.opacity = +s.opacity + .1) >= 1 ? s.display = "inline" : setTimeout(fade, speed)
  })();
}

fadeIn('s', 500)
<div id="s">asdfsadf</div>

Upvotes: 3

Related Questions