javascriptjqueryhtmlcssfadein

Implementing Fade in Fade Out on Array of Text in jQuery


I have an array of text that I'd like to iterate through and call the fadeIn and fadeOut functions in jQuery on.

var hellos = ["hi, i'm", "bonjour, je m'appelle", "hallo, ich heiße"]

The html code would look something like this:

<h2><span id="hellos"></span>Ch1maera</h2>

Ideally, on the front page of my website it would read something like "hi, i'm ch1maera" and then cycle through the different hellos, fading them in and then fading them out, while leaving "ch1maera" on the screen. If possible, I'd like to isolate the "ch1maera" from the hellos so that it stays in the same place and doesn't move depending on the length of the hellos in the list, if that makes sense. How would this be done?


Solution

  • You can set the text-align of h2 to right so that Ch1maera won't get moved by the hellos.

    var hellos = ["hi, i'm", "bonjour, je m'appelle", "hallo, ich heiße"];
    var index = 0;                                // index of the currently displayed hello
    $("#hellos").text(hellos[0]);                 // start by showing a hello
    
    (function animate() {                         // the function responsibe for the animation
      $("#hellos").fadeOut(1000, function() {     // first fadeOut #hellos
        index = (index + 1) % hellos.length;      // when fadeOut complete, increment the index (check if go beyond the length of the array)
        this.textContent = hellos[index];         // change text accordingly
      }).fadeIn(1000, animate);                   // then fadeIn. When fadeIn finishes, call animate again
    })();
    h2 {
      text-align: right;
      padding-right: 40%;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <h2><span id="hellos"></span> Ch1maera</h2>