JavaScript Text Scramble Effect

JavaScript Text Scramble Effect
Project: Text Scramble Effect
Author: Justin Windle
Edit Online: View on CodePen
License: MIT

The JavaScript code provides a text scrambling effect on a web page. It randomly replaces characters in the old text with random characters or displays a placeholder character, creating the scrambling effect. You can create an engaging visual effect where text characters appear to scramble and reveal a new set of characters.

The core functionality of the code lies in the TextScramble class, which takes an element as input and scrambles the text within it. By calling the setText method of the TextScramble instance and providing a new text, you can initiate the scrambling animation.

If you want to add an eye-catching and dynamic element to your web page, such as a headline or a banner with changing text, this code snippet quite fits your needs.

How to Create Text Scramble Effect using JavaScript

1. Create a div element with a class name “text” that will be used to load text dynamically. Wrap it into a container for further customization through CSS.

<div class="container">
  <div class="text"></div>
</div>

2. Now, use the following CSS styles for your text. You can modify the text size, font family and container styles according to your needs.

@import 'https://fonts.googleapis.com/css?family=Roboto+Mono:100';
body{
  font-family: 'Roboto Mono', monospace;
  background: #212121 !important;
  height: 450px;
}
.container {
  height: 100%;
  width: 100%;
  justify-content: center;
  align-items: center;
  display: flex;
}
.text {
  font-weight: 100;
  font-size: 28px;
  color: #fafafa;
}
.dud {
  color: #757575;
}

3. Lastly, add the following JavaScript code into your project to activate the text effect.

// ——————————————————————————————————————————————————
// TextScramble
// ——————————————————————————————————————————————————

class TextScramble {
  constructor(el) {
    this.el = el;
    this.chars = "!<>-_\\/[]{}—=+*^?#________";
    this.update = this.update.bind(this);
  }
  setText(newText) {
    const oldText = this.el.innerText;
    const length = Math.max(oldText.length, newText.length);
    const promise = new Promise(resolve => this.resolve = resolve);
    this.queue = [];
    for (let i = 0; i < length; i++) {
      const from = oldText[i] || '';
      const to = newText[i] || '';
      const start = Math.floor(Math.random() * 40);
      const end = start + Math.floor(Math.random() * 40);
      this.queue.push({ from, to, start, end });
    }
    cancelAnimationFrame(this.frameRequest);
    this.frame = 0;
    this.update();
    return promise;
  }
  update() {
    let output = "";
    let complete = 0;
    for (let i = 0, n = this.queue.length; i < n; i++) {
      let { from, to, start, end, char } = this.queue[i];
      if (this.frame >= end) {
        complete++;
        output += to;
      } else if (this.frame >= start) {
        if (!char || Math.random() < 0.28) {
          char = this.randomChar();
          this.queue[i].char = char;
        }
        output += `<span class="dud">${char}</span>`;
      } else {
        output += from;
      }
    }
    this.el.innerHTML = output;
    if (complete === this.queue.length) {
      this.resolve();
    } else {
      this.frameRequest = requestAnimationFrame(this.update);
      this.frame++;
    }
  }
  randomChar() {
    return this.chars[Math.floor(Math.random() * this.chars.length)];
  }}


// ——————————————————————————————————————————————————
// Example
// ——————————————————————————————————————————————————

const phrases = [
"Neo,",
"sooner or later",
"you're going to realize",
"Just as I did",
"that there's a difference",
"between knowing the path",
"and walking the path"];


const el = document.querySelector(".text");
const fx = new TextScramble(el);

let counter = 0;
const next = () => {
  fx.setText(phrases[counter]).then(() => {
    setTimeout(next, 800);
  });
  counter = (counter + 1) % phrases.length;
};

next();

You just need to customize the phrases array with your own set of phrases or words. Adjust the timing of the text transitions by modifying the setTimeout duration in the next function.

That’s all! hopefully, you have successfully created a text scramble effect using HTML, CSS, and JavaScript. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply