1

I want my code to fade text in and out using setInterval function in JavaScript. Currently it will only run my first piece of text and then keeps repeating the last bit over and over again. I'm not sure if it's JavaScript or my html.

<div class="col-md-3">
   <h3 id="RickQuotes" class="text-center">Rick "C137" Sanchez</h3><br />
      <h4 class="fade1">Hello</h4>  
</div>

<script>
    setInterval(function() {
    $('h4').fadeOut(1000, function() {
        var $this = $(this);
        $this.text($this.text() == ' Hello' ? 'Rick and Morty' : '.......');        
        $this.toggleClass('fade1');        
        $this.fadeIn(1000);
    });
}, 3000);
</script>
ncirl.eva
  • 15
  • 5

2 Answers2

0

It's because you test if the text is ' Hello' (by the way, I am not sure if the space before the 'Hello' is on purpose) and if yes, replace it by 'Rick and Morty', but if not replace it by "........"

The first time around, it will be false because your text will be "Hello" and not " Hello" with a space before the H, so it will replace it by "........"

Second time around, your text will be "......." which is also not equal to " Hello" so it will again be replaced by ".......", etc etc.

Try this if you want the order to always be the same:

<script>
    setInterval(function() {
    $('h4').fadeOut(1000, function() {
        var $this = $(this);

        const current_text = $this.text();
        const texts = ['Hello', '.....', 'Rick and Morty']
        let new_text = ""
        for( let i = 0; i < texts.Length; i++ )
        {
           if( current_text==texts[i] )
           {
              const n = i < texts.Length-1 ? i+1:0;
              new_text = texts[n];
              break;
           }
        }

        $this.text(new_text);        
        $this.toggleClass('fade1');        
        $this.fadeIn(1000);
    });
}, 3000);
</script>
Ryan Pergent
  • 4,432
  • 3
  • 36
  • 78
0

If you check $this.val() to find the next one you'll get in trouble when reaching .... as it can be followed by either Hello or Rick and Morty. You'll have to store the last printed value from 'Hello' and 'Rick and Morty' in order to deduce what follows '...'

Another solution would be having a sequence array and an outer index storing the next item to display. Increment index every loop and reset it when it reaches the length of the sequence.

var index = 0;
setInterval(function() {
    $('h4').fadeOut(1000, function() {
        var $this = $(this);

        var sequence = ['Hello','....', 'Rick and Morty', '....'];

        index = index == sequence.length ? 0 : index;
        $this.text(sequence[index++]);        
        $this.toggleClass('fade1');        
        $this.fadeIn(1000);

    });
}, 2000);

fiddle: https://jsfiddle.net/d82btd8m/1/

Alexandru Severin
  • 6,021
  • 11
  • 48
  • 71