kojo kojo - 2 months ago 8
Javascript Question

Animate contents of a changing element in JavaScript (Jquery)

'h1' in the code below counts from 0 to infinity. How do I animate every single number so that it fades in and out.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<h1 id="the_numbers">0</h1>

<script>
var output = $('h1');
var isPaused = false;
var time = 0;
var t = window.setInterval(function() {
if(!isPaused) {
time++;
output.text(time);
}
}, 1000);


$('.pause').on('click', function(e) {
e.preventDefault();
isPaused = true;
});

$('.play').on('click', function(e) {
e.preventDefault();
isPaused = false;
});
</script>

Answer

Use jquery fadeIn and fadeOut functions

var output = $('h1');
var isPaused = false;
var time = 0;
var t = window.setInterval(function() {
  if (!isPaused) {
    time++;
    output.fadeOut(500, function() {
      output.text(time);
    });

    output.fadeIn(500)
  }
}, 1000);


$('.pause').on('click', function(e) {
  e.preventDefault();
  isPaused = true;
});

$('.play').on('click', function(e) {
  e.preventDefault();
  isPaused = false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<h1 id="the_numbers">0</h1>

Comments