2

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)})();
}
4
  • 1
    Are you allowed to use jQuery in your task or somewhat? Commented Jun 19, 2015 at 5:00
  • I kinda want to avoid using a external library, but I'm aware that it'll make this so much easier. I would like a solution in vanilla JavaScript. Commented Jun 19, 2015 at 5:03
  • 1
    Yes. It would be $('#" + id).fadeOut(2000) where 2000 is 2 seconds :) Just in case you will use it. Commented Jun 19, 2015 at 5:05
  • I'll be sure to use this when I play around with JQuery more in the future. Thanks :) Commented Jun 19, 2015 at 5:10

2 Answers 2

3

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.