Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div class='o-content  o-content__intro'>
  <div class="o-content__intro--container">
    <div class="c-word  c-word__fn  c-word--big  c-word--heavy  c-word--brand  c-word--slick">Text</div>
    <div class="c-letters-group">
      <div class="c-word  c-word__ln  c-word--big  c-word--heavy  c-word--brand">Animation</div>
    </div>
    <button href='#' tag="button" class="c-btn  c-btn--bright  c-btn--medium  c-btn__ui-show  u-ch">
      Enter
    </button>
  </div>
</div>

<button class="c-btn  c-btn--bright  c-btn--medium c-btn__restart" style="position:absolute; bottom:10px; right: 10px">Restart</button>
              
            
!

CSS

              
                // the CSS is defined in the settings
              
            
!

JS

              
                // The settings object (do not use any delay values... leads to unexpected & undesireable results)
let SETTINGS = {
  states: {
    introAnimationTextsAlreadyBuilt: false,
    introActive: null
  },
  ui: {
    btns: {
      cBtnUiShow: {
        el: document.querySelector(".c-btn__ui-show"),
        tweenParamsTo: {
          hide: {
            autoAlpha: 0
          },
          show: {
            autoAlpha: 1
          }
        },
        status: "hidden"
      }
    },
    container: {
      cContentIntroContainer: {
        el: document.querySelector(".o-content__intro--container"),
        tweenParamsTo: {
          hide: {
            autoAlpha: 0
          },
          show: {
            autoAlpha: 1
          }
        },
        status: "hidden"
      }
    },
    // This section hold the letters of the words (fn = firstname, ln = lastname) of
    // intro container the to be animated (should be renamed to sth better)
    intro: {
      cWordFn: {
        el: document.querySelector(".c-word__fn"),
        letters: "",
        lettersTotal: null,
        parentElem: "",
        tweenParamsTo: {
          hide: {},
          show: {}
        },
        txt: "",
        status: "shown"
      },
      cWordLn: {
        el: document.querySelector(".c-word__ln"),
        letters: "",
        lettersTotal: null,
        parentElem: "",
        tweenParamsTo: {
          hide: {},
          show: {}
        },
        txt: "",
        status: "shown"
      }
    }
  },
  gsapGlobals: {
    duration: 0.25,
    ease: "easeInOut"
  },
  // Collections have to be defined manually at the moment.
  collectedObjs: {
    intro_allLogoTxtElems: {
      collection: [],
      delay: 0,
      duration: 0.75,
      staggerDelay: 0.05,
      tweenParamsTo: {
        hide: {
          opacity: 0,
          scale: 0.05
        },
        show: {
          opacity: 1,
          scale: 1
        }
      },
      parentContainerCssClass: "o-content__intro--container"
    }
  },
  helpers: {
    activeCollectionDuringSetup: "",
    totalElems: 0
  }
};

/* -----------------------------------------------------------------------------
 * Main animation functions
 * ----------------------------------------------------------------------------*/

// Build Intro Animation.
function introAnim(reverse = false) {
  let tl = new TimelineMax({
    paused: true,
    onComplete: cb_onComplete, // <-- this callback fires BEFORE the nested word animation(s) is/are finished - why?
    onReverseComplete: cb_onReverseComplete
  });
  tl.add("startIntroAnim", 0);

  // These 2 'set' function only make sure, that the 2 DOM elements have their correct settings in the beginning:
  // container = opacity: 1; button = opacity: 0
  tl.set(
    SETTINGS.ui.btns.cBtnUiShow.el,
    SETTINGS.ui.btns.cBtnUiShow.tweenParamsTo.hide,
    "startIntroAnim"
  );
  tl.set(
    SETTINGS.ui.container.cContentIntroContainer.el,
    SETTINGS.ui.container.cContentIntroContainer.tweenParamsTo.show,
    "startIntroAnim"
  );

  // Make the whole container visible... but: we did that in the setting above. All contained elements are set to "opacity: 0" - see
  // prepareText(), where every letter is wrapped in a span with "opacity: 0" assigned.
  // tl.add(toggleVisibilityOfElem(SETTINGS.ui.container.cContentIntroContainer, "show"), "startIntroAnim");
  // animate the words (staggered fade-in)
  tl.add(introAnimTweenWordOpening().play(), "startIntroAnim+=0.5");
  // fade-in the ENTER button: when this tween is finished, this timeline's onComplete is fired - which is NOT good,
  // since the nested staggered tween might still be doing their work...
  tl.add(
    toggleVisibilityOfElem(SETTINGS.ui.btns.cBtnUiShow, "show", 1),
    "-=0.25"
  ); // <-- from the end of the timeline

  if (!reverse) {
    tl.play().timeScale(1);
  } else {
    tl.reverse(0).timeScale(2.5);
  }

  // Do I need a return statement here?
  // What, if I want to cancel the aniamtion from somewhere else?
  return tl;
}

// Staggered nested tweens. The problem here is, that the
// onComplete callback is fired AFTER the main timeline's one.
function introAnimTweenWordOpening() {
  let tl = new TimelineMax({
    paused: true,
    // Here is the TimelineMax's acllback
    onComplete: function() {
      console.log(
        ">>> Finished introAnimTweenWordOpening. Should fire BEFORE the parent's onComplete callback! But does not do so! Why?"
      );
    }
  });

  tl.staggerFromTo(
    SETTINGS.collectedObjs.intro_allLogoTxtElems.collection,
    SETTINGS.collectedObjs.intro_allLogoTxtElems.duration,
    SETTINGS.collectedObjs.intro_allLogoTxtElems.tweenParamsTo.hide,
    SETTINGS.collectedObjs.intro_allLogoTxtElems.tweenParamsTo.show,
    SETTINGS.collectedObjs.intro_allLogoTxtElems.staggerDelay,
    0,
    cb_finishedTweeningIntroText
  );

  // tl.play();
  return tl;
}

function toggleVisibilityOfElem(elem, visibility, delay = 0) {
  let toParams;

  if (visibility === "hide" || visibility === "hidden") {
    toParams = elem.tweenParamsTo.hide;
  } else {
    toParams = elem.tweenParamsTo.show;
  }
  toParams.delay = delay;

  // Set state of element to intro or visible/show or hidden
  elem.status = visibility;

  // TODO: use a global SETTINGS value instead of 0.25
  return new TweenMax.to(elem.el, SETTINGS.gsapGlobals.duration, toParams);
}

/* -----------------------------------------------------------------------------
 * Callback functions
 * ----------------------------------------------------------------------------*/

let cb_onComplete = function() {
  console.log("> CB onComplete; if intro, set 'states.introActive=true'");
};

let cb_onReverseComplete = function() {
  console.log("> CB onReverseComplete");
};

let cb_finishedTweeningIntroText = function() {
  console.log("> CB Finished tweening nested staggered intro text anim.");
};

/* -----------------------------------------------------------------------------
 * The function that start the animation
 * ----------------------------------------------------------------------------*/

function init() {
  // Prepare the text, if required:
  if (!SETTINGS.states.introAnimationTextsAlreadyBuilt) {
    prepareIntroTexts();
  }

  if (SETTINGS.states.introAnimationTextsAlreadyBuilt) {
    introAnim();
  } else {
    console.warn("\n> The text of the intro is not prepared to be animated.");
  }
}

// "removeIntro" called: The intro animation should be played in reverse now and fire an event, when complete.
// But it does not. Instead, the button fades out and then, along with the letters\' aniamtion, in again. Why?
function removeIntro() {
  introAnim(true); // "true means": reverse=true, does not work!
}

/* -----------------------------------------------------------------------------
 * Add eventListener to buttons
 * ----------------------------------------------------------------------------*/

SETTINGS.ui.btns.cBtnUiShow.el.addEventListener("click", removeIntro);

// Restart Button (only for Demo purposes, therefore not added to SETTINGS)
let restartBtn = document.querySelector(".c-btn__restart");
restartBtn.addEventListener("click", init);

/* -----------------------------------------------------------------------------
 * Call the initialize function to start the animation
 * ----------------------------------------------------------------------------*/

init();

/* -----------------------------------------------------------------------------
 * HINT:
 * Below this point are functions that are needed for functionality, but they
 * are irrelevant for the problem of this pen.
 * ----------------------------------------------------------------------------*/

/* -----------------------------------------------------------------------------
 * Prepare text:
 * Make each letter of a word animateable by wrapping it into a span.
 *
 * - Search for a block with a specific class
 * - get innterText
 * - wrap each letter in a span
 * - delete the "old" innerText and assign new content (the span-wrapped word)
 *   and assign each letter a style of opacity=0 
 *
 * Prepare all the intro-related texts. Don't leave any SETTINGS.ui.intro elements out -> will cause error!!!
 * Last param: do NOT add a dot / hash in front of the css selector!!!
 * Only build (that is: collect and save them to the settings object) the intro text, when necessary:
 * ----------------------------------------------------------------------------*/
function prepareIntroTexts() {
  // Get the texts of the intro container:

  // First name
  _getDOMContent(
    SETTINGS.ui.intro.cWordFn.el,
    SETTINGS.ui.intro.cWordFn,
    SETTINGS.collectedObjs.intro_allLogoTxtElems.parentContainerCssClass,
    "intro_allLogoTxtElems", // must be predefined in SETTINGS
    "cWordFn"
  );

  // Last name
  _getDOMContent(
    SETTINGS.ui.intro.cWordLn.el,
    SETTINGS.ui.intro.cWordLn,
    SETTINGS.collectedObjs.intro_allLogoTxtElems.parentContainerCssClass,
    "intro_allLogoTxtElems",
    "cWordLn"
  );

  // Now delete the original text content and re-assign it using the 'thisNode' string from
  // SETTINGS.ui[thisNode]. The parameter delivers the subNode of the SETTINGS
  // object, whose content shall be retrieved
  _swapTexts(SETTINGS.ui.intro);

  // Let the settings know that the intro texts are now built
  SETTINGS.states.introAnimationTextsAlreadyBuilt = true;
}

// Get Text from DOM element and wrap each letter in a span
function _getDOMContent(
  node,
  localSettings,
  parentContainerCssClass,
  collection,
  settingsUiElem
) {
  // console.log(' ')
  // console.log('_getDOMContent:')
  // console.log('node =', node);
  // console.log('localSettings =>', localSettings)
  // console.log('parentContainerCssClass =>', parentContainerCssClass)
  // console.log('node.textContent.trim() =', node.textContent.trim());
  // console.log('collection =', collection)

  let letterArr = [], // save wrapped letters to this array
    nodeTxt = "",
    nodeLen = 0;

  // Some node do not have textContent, so check here!
  if (typeof node.textContent === "string" || typeof node.textContent === "") {
    nodeTxt = node.textContent.trim();
    nodeLen = nodeTxt.length;
  }

  // To setup a new collection, reset the counter
  // Beware: there can be more than just one textNode from a collection!
  // However, this is a bad solution. Better to check, if the text is already
  // there or not, or if the whole object needs to be rebuild.
  if (collection !== SETTINGS.helpers.activeCollectionDuringSetup) {
    SETTINGS.helpers.totalElems = 0;
  }

  // Set the current collection (a DOM element / CSS class of which the texts are children)
  // Must be pre-defined in the Settings object!
  SETTINGS.helpers.activeCollectionDuringSetup = collection;

  // If the node has letters...
  if (nodeLen > 0) {
    // ... loop over all letters and wrap them in a span element
    for (let i = 0; i < nodeLen; i++) {
      // Since we want to count ALL DOM elements that shall be animated in one stagger animation,
      // we need a variable, that counts over ALL of the elements, not just within a group / word.
      // Otherwise the CSS class numbering will be false.
      let newElem = document.createElement("span");
      let newTxtNode = document.createTextNode(nodeTxt[i]);

      newElem.appendChild(newTxtNode);
      newElem.classList.add(
        "c-letter",
        "c-letter-" + ++SETTINGS.helpers.totalElems,
        "c-child-letter-of--" + parentContainerCssClass,
        "c-child-letter-" + (i + 1)
      );

      // Special coloring for special character(s)
      if (nodeTxt[i] === "&") {
        newElem.classList.add("u-color-primary-light");
      }

      letterArr.push(newElem);

      // Save elements to collectedObjs, except empty spaces, which don't need to be animated
      // (would make the animation uneven)
      if (nodeTxt[i] !== " ") {
        SETTINGS.collectedObjs[collection].collection.push(newElem);
      }
    }
  }

  // Assign the wrapped letters to the SETTINGS object of the element
  localSettings.letters = letterArr;
  localSettings.lettersTotal = nodeLen;
  localSettings.parentElem = node;
  localSettings.txt = nodeTxt;
}

// Replace original text with 'spanned' version; depends on _getDOMContent
function _swapTexts(settingsSubNode) {
  for (let i in settingsSubNode) {
    let el = settingsSubNode[i];

    // Only proceed, if a special property is given in the SETTINGS object tree (e.g. 'el';
    // 'divider' for example does not have such an 'el' property, but all text nodes do)
    if (el.hasOwnProperty("el")) {
      // Clear out the original text in the DOM element
      el.parentElem.innerText = "";

      // Now append the text again, but with its new wrappings
      for (i in el.letters) {
        el.parentElem.appendChild(el.letters[i]);
        el.letters[i].style.opacity = 0;
      }
    }
  }
}

// ---------------------------------------------------------------------------------------------------------
//
// Here ist stuff that shold be done with "reverse", which is currently not working...
//
// Dissolve Intro Animation
// TODO: GSAP has a reverse function. Use that on the introAnim instead of creating anew function
//       -> Does not work at the moment
function introAnimReverse() {
  console.log(" ");
  console.log("---> introAnimReverse called");

  this.$store.commit("toggleUIState", true, "visible");
  //  this.toggleUIState(true, 'visible')

  let tl = new TimelineMax({
    paused: true
  });

  tl.add("startIntroAnimReverse", 0);

  //tl.addCallback(this.toggleUIState, 0, [true, 'visible'])

  tl.add(
    this.toggleVisibilityOfElem(
      SETTINGS.ui.container.cContentIntroContainer,
      "hide"
    ),
    "startIntroAnimReverse"
  );
  tl.add(this.introAnimTweenWordClosing(true), "startIntroAnimReverse+=0.15");
  tl.add(this.introAnimTweenLineIn(true), "startIntroAnimReverse+=0.5");
  tl.add(
    this.toggleVisibilityOfElem(SETTINGS.ui.btns.cBtnUiShow, "hidden"),
    "startIntroAnim=+0.75"
  );

  tl.play();
  return tl;
}

// ...used in the introAnimReverse function...
function introAnimTweenWordClosing() {
  // console.log(' ')
  // console.log('---> tween word reverse called');

  let tl = new TimelineMax({
    paused: true
  });

  // Use negative stagger Delay value to make GSAP read the array from behind
  tl.staggerFromTo(
    SETTINGS.collectedObjs.intro_allLogoTxtElems.collection,
    SETTINGS.collectedObjs.intro_allLogoTxtElems.duration,
    SETTINGS.collectedObjs.intro_allLogoTxtElems.tweenParamsTo.show,
    SETTINGS.collectedObjs.intro_allLogoTxtElems.tweenParamsTo.hide,
    -SETTINGS.collectedObjs.intro_allLogoTxtElems.staggerDelay,
    0,
    this.finishedTweeningIntroTextReverse
  );
  tl.timeScale(2.5);
  tl.play();
  return tl;
}

              
            
!
999px

Console