1

I am trying to make it so that when i hover my div it does a "hacker" effect on the text inside and transitions it from just random letters into an actual word, then once i stop hovering, it does the same effect. either back to the "random" pre-written letters, or if possible actually random letters

This is the Code i currently have, the first 2 lines are to check if the element is on the current webpage as its apart of a multi web-page code.

let pxScreen1 = document.getElementsByClassName("screen1");

if ( pxScreen1 !== null ) {

  const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

  let interval = null;

  const screen = document.querySelector(".screen1"),
        name = document.querySelector(".name1");

  screen.onmouseenter = event => {  
    let iteration = 0;
    
    clearInterval(interval);
    
    interval = setInterval(() => {
      name.innerText = name.innerText
        .split("")
        .map((letter, index) => {
          if(index < iteration) {
            return name.dataset.value[index];
          }
        
          return letters[Math.floor(Math.random() * 26)]
        })
        .join("");
      
      if(iteration >= name.dataset.value.length){ 
        clearInterval(interval);
      }
      
      iteration += 1 / 3;
    }, 40);
  }
}
f1sh
  • 11,489
  • 3
  • 25
  • 51
Ariiles
  • 13
  • 2

1 Answers1

1

I would use a scrambler function that can append a random string of characters to a solved string - to get the effect of unscrambling characters one by one:

// https://stackoverflow.com/a/27872144/383904
const randomString = (n, r='') => {
  while (n--) r += String.fromCharCode((r=Math.random()*62|0, r+=r>9?(r<36?55:61):48));
  return r;
};

const unscramble = (el) => {
  const chars = [...el.dataset.scramble];
  const tot = chars.length;
  
  let iteration = 0;
  let ch = 0;
  let solved = "";
  
  el._itv = setInterval(() => {

    if (iteration > 10) {
      iteration = 0;
      solved += chars[ch];
      ch += 1;
    }
    
    el.textContent = randomString(tot - ch, solved);
    
    if (ch === tot) {
      clearInterval(el._itv);
    }
    iteration += 1;
  }, 30);
};

const scramble = (el) => {
  clearInterval(el._itv);
  el.textContent = randomString([...el.dataset.scramble].length)
};

const scrambler = (el) => {
  el.addEventListener("mouseenter", unscramble.bind(null, el));
  el.addEventListener("mouseleave", scramble.bind(null, el));
  scramble(el);
};

document.querySelectorAll("[data-scramble]").forEach(scrambler);
[data-scramble] { font: 2rem/1.4 monospace; }
Hover and keep hovering :)
<div data-scramble="Hello, World!">asd</div>
<div data-scramble="Stack Overflow">asd</div>

You can find more about that randomString(totChars, resultPefix) in this answer: Generate random string of characters

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313