Search code examples
javascriptcycle

Using JavaScript to have a text line cycle between various text


The idea is to have the subheader under the header cycle between text endlessly on page load.

Example:

HEADER

SUBHEADER 1

wait one second

HEADER

SUBHEADER 2

wait one second

HEADER

SUBHEADER 3

etc.

HTML:

                    <header class="hero-title hero-box">
                        <h1>Ninety9Balloons</h1>
                        <h2>Entertainment</h2>
                       <div class="sub-header">
                            <h3>Editing</h3>
                            <h3>Color</h3>
                            <h3>VFX</h3>
                            <h3>Motion Graphics</h3>
                        </div>
                    </header>

For one second EDITING will be under Entertainment, then it cycles to COLOR, then VFX, etc. and repeats back to EDITING


Solution

  • HTML:

    <header class="hero-title hero-box">
      <h1>Ninety9Balloons</h1>
      <h2>Entertainment</h2>
      <div class="sub-header">
        <h3 id="dynamic-sub-head">Editing</h3>
      </div>
    </header>
    

    JAVASCRIPT:

    const subHeads = ['Color', 'VFX', 'Motion Graphics', 'Entertainment'];
    let displayIdx = 0;
    
    setInterval(() => {
      document.getElementById('dynamic-sub-head').innerHTML = subHeads[displayIdx];
      displayIdx += 1;
      if (displayIdx >= subHeads.length) {
        displayIdx = 0;
      }
    }, 1000);