Home > Blockchain >  JQuery how to make transition on setTimeout text change
JQuery how to make transition on setTimeout text change

Time:10-26

how do I make every text change have a fadein and fade out transition, if I give a 5 second interval how do I give a fade out and fade in

let timer = 0;
do_test(timer);

function do_test(timer){
  timer  ;
  if (timer > 29){
    $('body').css('background','blue');
  }else if (timer > 20){
    $('body').css('background','green');
  }else if (timer > 10){
    $('body').css('background','pink');
  }else if (timer > 3){
    $('body').css('background','yellow');
  }
  $('#cnt').text(timer);
  if (timer < 40){
    setTimeout(() => {do_test(timer)},500);
  } else {
    $('body').html('<div id="dun">DONE</div>');
  }
}

this html

<div id="cnt"></div>

CodePudding user response:

You can use fadeIn and fadeOut

let timer = 0;
do_test(timer);
const body = $("body");

function do_test(timer){
  timer  ;
  const elem = $("#cnt");
  elem.fadeOut(500, function () {
    elem.text(timer);
    if (timer===10) body.css('background','green');
    else if (timer===25) body.css('background','yellow');
    else if (timer===30) body.css('background','red');
    elem.fadeIn(500, function () {
      if (timer < 50) do_test(timer);
    });
  });
}
body {
  transition: background .5s linear;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="cnt"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You will need to use setInterval for this. Find out more about the difference between the two: setTimeout or setInterval?

const $body = $('body'), cnt = $('#cnt');
let i = 0;
let do_test = setInterval(function() {
  i  ;
  if (i > 0 && i < 2){
    setBg($body, 'blue');
  }else if (i >2 && i < 4){
    setBg($body, 'green');
  }else if (i > 4 && i < 6){
    setBg($body, 'pink');
  }else if (i > 6 && i < 8){
    setBg($body, 'yellow');
  }
  if(i >= 10){
    clearInterval(do_test);
    cnt.text('DONE');
    return;
  }
  cnt.text(i);

},1000);

function setBg(sel, col){
  sel.css('background',col);
}
#cnt {
  text-align: center;
  font-size: 30px;
  line-height: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="cnt"></div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related