Fading in text with jQuery

This question already has an answer here:

Is there a way to fade in the text when it changes? I'm using jQuery's html() function. I attempted doing it with fadeOut(), but now it's going back and forth between the fadeIn and fadeOut.

Please let me know if there's a better way to do this, does the constant check on browser resize worse than detect if width is a certain size?

https://jsfiddle.net/jzhang172/uhmubhtf/2/

$(function(){
  function screenClass() {
  
  if ($( window ).width() <500){
$(".ok span").html("no");
}
else{
$(".ok span").fadeOut();
$(".ok span").fadeIn().html("yes");
}

  }
  $(window).bind('resize',function(){
  screenClass();
  });
  
  
  });
.ok{
  background:blue;
  height:300px;
  width:300px;
  transition:1s;
  font-size:30px;
  color:white;
}
.span{
  color:white;
  font-size:30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ok"><span></span></div>

Answers 1

  • I can't comment yet? I have clone your fiddle and changed the javascript code just a little bit.

    https://jsfiddle.net/LoicMars/3gr8fnfn/

    $(function() {
      yes = true;
      no = true;
    
      function screenClass() {
        if ($(window).width() < 500 && yes == true) {
          $(".ok span").fadeOut(function() {
            $(this).fadeIn().html("no");
            yes = false;
            no = true;
          });
        } else if ($(window).width() >= 500 && no == true) {
          $(".ok span").fadeOut(function() {
            $(this).fadeIn().html("yes");
            yes = true;
            no = false;
          });
        }
      }
      $(window).bind('resize', function() {
        screenClass();
      });
    });
    

    I have add 2 variables for preventing the constant fading blink effect when resizing.


Related Articles