Search code examples
javascriptjqueryfadeinfadeoutcycle

Cycle through text with overlap


I am trying to cycle through single words that will fade in/fade out and can get this working, although I would like to make it so there is a slight overlap between words before the first one completely disappears.

var divs = $('div[id^="title-"]').hide(),
  i = 0;

(function cycle() {
  divs.eq(i).fadeIn(800).delay(600).fadeOut(700, cycle);
  i = ++i % divs.length;
})();
#title-1,
#title-2,
#title-3 {
  font-size: 10vw;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div id="title-1">Bam</div>
<div id="title-2">Bang</div>
<div id="title-3">Blah</div>

Fiddle: https://jsfiddle.net/2020_RG/8fhqbcw5/


Solution

  • To have the text effect overlap between words you can use setTimeout() to display the next word slightly ahead of displaying the next. You cannot achieve this with the fadeOut() callback as that only fires when the previous animation has completed.

    To make this work, define a timeout which will run slightly before all actions queued on the element complete. In the example below I user a 300ms overlap, but this can be amended as you require.

    Also note that for the words to occupy the same space in the DOM their CSS position would need to be set to absolute, fixed or sticky.

    var divs = $('div[id^="title-"]'),
      i = 0;
    
    (function cycle() {
      divs.eq(i).fadeIn(800).delay(600).fadeOut(700);
      i = ++i % divs.length;
      setTimeout(cycle, 1800);
    })();
    #title-1,
    #title-2,
    #title-3 {
      font-size: 10vw;
      position: absolute;
      display: none;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <div id="title-1">Bam</div>
    <div id="title-2">Bang</div>
    <div id="title-3">Blah</div>