Search code examples
javascriptjqueryhtmlfadein

Fixing Fading Text Using fadeToggle() in JQuery


I'm trying to use fadeToggle() to make text from an array fade in, wait 10 seconds, than fade out for another text to do the same thing.

This code makes the text switch every few seconds perfectly, i just can't get the right code to make it fade in/out:

var texts = [" \" It's really hard to design products by focus groups. A lot of times, people don't know what they want until you show it to them. \" <br /> ~ Steve Jobs ", " \"  Design is not just what it looks like and feels like. Design is how it works \" <br /> ~ Steve Jobs", " \" That’s been one of my mantras — focus and simplicity. Simple can be harder than complex ; you have to work hard to get your thinking clean to make it simple. \" <br /> ~ Steve Jobs", " \" The present is theirs ; the future, for which I really worked, is mine. \" <br /> ~ Nikola Tesla ", " \” The value of an idea lies in the using of it. \“ <br /> ~ Thomas Edison "];
var count = 0;

$(document).ready(function() {
  function changeText() {
    $(".quote").html(texts[count]);
    count < texts.length ? count++ : count = 0;
  }

  setInterval(changeText, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 class="quote">Hello</h1>


Solution

  • You can follow this logic:

    1. Fade out.
    2. Change text.
    3. Fade in.

    var texts = [" \" It's really hard to design products by focus groups. A lot of times, people don't know what they want until you show it to them. \" <br /> ~ Steve Jobs ", " \"  Design is not just what it looks like and feels like. Design is how it works \" <br /> ~ Steve Jobs", " \" That’s been one of my mantras — focus and simplicity. Simple can be harder than complex ; you have to work hard to get your thinking clean to make it simple. \" <br /> ~ Steve Jobs", " \" The present is theirs ; the future, for which I really worked, is mine. \" <br /> ~ Nikola Tesla ", " \” The value of an idea lies in the using of it. \“ <br /> ~ Thomas Edison "];
    var count = 0;
    
    $(document).ready(function() {
      function changeText() {
        $(".quote").fadeOut(250, function () {
          $(this).html(texts[count]).fadeIn(250);
        });
        count < texts.length ? count++ : count = 0;
      }
      setInterval(changeText, 2000);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <h1 class="quote">Hello</h1>