Attempting to create a dynamic effect with a div element, where a randomly generated string shifts to the left and new characters are continuously added at the end, resembling a scrolling motion

I recently delved into learning javascript, html, and css on Codepen. I've been working on creating a matrix code rain effect over the past few days. While I do have some experience with other programming languages, I encountered an issue when trying to save and shift generated strings in arrays for later use. Instead of shifting the string over by one character and adding a new random character, the entire array named store was being overwritten with the most recent string.

Below is the javascript code I used (including console logs for debugging purposes):

var numDivs = 10;
var pos = [];
var delay = [];

/* Check page is loaded and create each of the divs for the 'raindrops' */
for (let i = 0; i < numDivs; i++) {
  document.addEventListener('DOMContentLoaded', function() {
      var div = document.createElement('div');
      div.id = 'matrix'+i;
      div.className = 'matrixC m'+i;

      document.body.appendChild(div);
  }, false);
}

/* Generate 12 character string for each of the 'raindrops' */
var characters = [...];

var store = [];
var state2 = "false";

function genNum() {
  var stringArr = [];
  for (let n = 0; n < numDivs; n++) {
    var finalString = "";
    var char = 0;
    if (state2 == "false"){
      var state = "false";
    }
    
    if (state == "false"){
      for (let m = 0; m < 20; m++) {
        let char = characters[Math.floor(Math.random() * characters.length)];
        finalString += char;
        stringArr[m] = char;
      }
      state = "true";
    }
    else {
      ...
    }
    ...
  }
  state2 = "true";
}

setInterval(genNum, 100); /* Regenerate string from above every 0.15s */

...

If you require it, here is my CSS as well:

body {
  background-color: black;
}

.matrixC {
  transform: translate(-200%,-200%);
  font-size: 10px;
  width: 5px;
  display: inline-block;
  text-align: center;
  word-wrap: break-word;
  background: linear-gradient(black, #d0ebc4);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  text-shadow: 0 0 20px #70ea37;
  margin: -5px;
}

I attempted moving the store state around in the code and even tried using switch cases to specify which part of the array to modify but the same error persisted.

Answer №1

I managed to make some adjustments to the code, although it may not be the most efficient solution. Here's what I modified:

else {
  for (let c = 0; c < 20; c++){
    stringArr[c] = store[c+n*20].slice(); // Create a copy of the array
  }
  stringArr.shift();
  let char = characters[Math.floor(Math.random() * characters.length)];
  stringArr[19] = char;
  finalString = stringArr.join('');
}
for (let b = 0; b < 20; b++){
  store[b+n*20] = stringArr[b];
}
document.getElementById("matrix"+n).innerHTML = finalString;

Now the entire program looks like this:

var numDivs = 100;
var pos = [];
var delay = [];

/* Check page is loaded and create each of the divs for the 'raindrops' */
for (let i = 0; i < numDivs; i++) {
  document.addEventListener('DOMContentLoaded', function() {
      var div = document.createElement('div');
      div.id = 'matrix'+i;
      div.className = 'matrixC m'+i;

      document.body.appendChild(div);
  }, false);
}

/* Generate 12 character string for each of the 'raindrops' */
var characters = ["日", "ハ","ミ","ヒ","ー","ウ","シ","ナ","モ","ニ","サ","ワ","ツ","オ","リ","ア","ホ","テ","マ","ケ","メ","エ","カ","キ","ム","ユ","ラ","セ","ネ","ス","タ","ヌ","ヘ","0","1","2","3","4","5","7","8","9","Z",":","・",".",'"',"=","*","+","-","<",">","¦","|","ç","ク"];

var store = [];
var state2 = "false";

function genNum() {
  var stringArr = [];
  for (let n = 0; n < numDivs; n++) {
    var finalString = "";
    var char = 0;
    if (state2 == "false"){
      var state = "false";
    }
    
    if (state == "false"){
      for (let m = 0; m < 20; m++) {
        let char = characters[Math.floor(Math.random() * characters.length)];
        finalString += char;
        stringArr[m] = char;
      }
      state = "true";
    }
    else {
      for (let c = 0; c < 20; c++){
        stringArr[c] = store[c+n*20].slice(); // Create a copy of the array
      }
      stringArr.shift();
      let char = characters[Math.floor(Math.random() * characters.length)];
      stringArr[19] = char;
      finalString = stringArr.join('');
    }
    for (let b = 0; b < 20; b++){
      store[b+n*20] = stringArr[b];
    }
    document.getElementById("matrix"+n).innerHTML = finalString;   
  }
  state2 = "true";
}

setInterval(genNum, 150); /* Regenerate string from above every 0.15s */

let root = document.documentElement;
for (let i = 0; i < numDivs; i++) {
  pos[i]=((Math.random() * 100) + "vw"); /* Set random position across page */
}
for (let i = 0; i < numDivs; i++) {
  delay[i]=((Math.random() * 10) + "s"); /* Set random offset time for start of animation */
}


let dynamicStyles = null;

function addAnimation(body) { /* create animation function using parsed code */
  if (!dynamicStyles) {
    dynamicStyles = document.createElement('style');
    dynamicStyles.type = 'text/css';
    document.head.appendChild(dynamicStyles);
  }

  dynamicStyles.sheet.insertRule(body, dynamicStyles.length);
}

for (let i = 0; i < numDivs; i++) { /* For each 'raindrop' create animation from random point across page down to off-screen */
  addAnimation(`
  @keyframes fall`+i+` { 
    from {
      transform: translate(`+pos[i]+`,-150%);
    } 
    to {
      transform: translate(`+pos[i]+`,100vh);
    }
   }`);
}

/* Give each div their corresponding animation, specifying all details */
document.addEventListener("DOMContentLoaded", function () {
  for (let i = 0; i < numDivs; i++) {
    document.getElementById("matrix"+i).style.animation = "fall"+i+" 5s linear "+delay[i]+" infinite"; 
  }
});
body {
  background-color: black;
}

.matrixC {
  transform: translate(-200%,-200%); /* Make sure none are on screen at start*/
  font-size: 15px;
  width: 10px; /* Keeps text vertical */
  display: inline-block;
  text-align: center;
  word-wrap: break-word; /* Keeps text vertical */
  background: linear-gradient(black, #70ea37, #d0ebc4 80%); /* Creates fade effect from bottom to top */
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  text-shadow: 0 0 25px #70ea37;  /* Creates glow */
  margin: -5px; /* For some reason makes it more evenly spread */
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error Encountered When Updating cGridView in Yii: "TypeError: $.fn.yiiGridView is undefined"

I'm encountering an issue with updating the gridview TypeError: $.fn.yiiGridView is undefined; after using AjaxLink Click Button for Refresh <script> $(document).ready(function(){ $("#tombol_refresh").click(function(){ $.fn.yiiGridView ...

Unleash the power of a module by exposing it to the global Window object using the dynamic

In my development process, I am utilizing webpack to bundle and manage my TypeScript modules. However, I am facing a challenge where I need certain modules or chunks to be accessible externally. Can anyone guide me on how to achieve this? Additional conte ...

An external script containing icons is supposed to load automatically when the page is loaded, but unfortunately, the icons fail to display

Hello and thank you for taking the time to read my query! I am currently working in a Vue file, specifically in the App.vue where I am importing an external .js file containing icons. Here is how I import the script: let recaptchaScript2 = document.creat ...

The placement of my image shifts when I switch to the mobile view

Having a small issue with my image alignment. When I switch from portrait to landscape view, the image is no longer centered. The margin remains the same as in portrait view and I'm unsure how to adjust it. I've attempted changing the margins of ...

Tips for notifying the user about incorrect login credentials in Ionic 3

I'm attempting to implement a notification system using showAlert to inform users when they enter an incorrect email or password, but I'm having difficulty achieving this using try and catch statements Would it be feasible for me to use try and ...

Next.js React Server Components Problem - "ReactServerComponentsIssue"

Currently grappling with an issue while implementing React Server Components in my Next.js project. The specific error message I'm facing is as follows: Failed to compile ./src\app\components\projects\slider.js ReactServerComponent ...

What is the process for accessing a URL using a web browser and receiving a plain text file instead of HTML code?

Hello there! I've created a simple HTML file located at that can display your public IP address. If you take a look at the code of the page, you'll notice that it's just plain HTML - nothing fancy! However, I'm aiming for something mo ...

Steps For Adding Margins To A ProgressBar In Bootstrap To Give It A Spaced Look

Currently, I am endeavoring to design a progress bar that includes some spacing from the edges. The desired end result can be seen in the image below: https://i.sstatic.net/IvMFS.png The visual displays a red line within the gray progress bar, which is e ...

Step-by-step guide for creating a "load more on scroll" feature with Node.js and MongoDB

I currently have a Node server utilizing Express+Typescript to connect to a MongoDB database using Mongoose. Within the database, there is a collection named Products that the frontend (Angular 9) requests in order to display them. At the moment, the serv ...

arrange the elements in a specified sequence

I am trying to sort an array in a specific order var customOrder = { "1st Presentation / Meeting": 0, "Follow-On Meetings": 1, "Hold\/Uncategorized": 2, "MGL": 3, "PGL": 4, "BGL": 5, "RGL": 6, "SGL": 7, "Uncategorized Leads": 8, ...

Issue with custom fonts not showing in PDFs when using Puppeteer, even though they are displayed in screenshots

I've been working on dynamically creating PDF files using the puppeteer library, but I'm facing an issue where the generated PDF doesn't display the custom fonts (.woff) that I have specified. Instead, it defaults to using the system font, T ...

Tips for retrieving next-auth authOptions from an asynchronous function

I need to retrieve values from AWS Secrets Manager and integrate them into the authOptions configuration for next-auth. The code implementation I have is as follows: export const buildAuthOptions = async () => { const secrets: AuthSecrets = await getS ...

Creating a UI Component when clicking on something

Currently, I am immersed in a project and had a question regarding the possibility of rendering UI components on click. In other words, is it feasible to trigger component rendering through an onclick event? For instance, consider the following example: & ...

There is a plethora of mistakes present in classes that involve constructors and functions

Below is the code snippet for my file: #include <iostream> #include <string> #include <cstdio> #include <fstream> class Sphere{ private: int x; int y; int r; public: Sphere(); void set_x(int first) ...

Creating a PDF document using html2pdf: A step-by-step guide

Currently, I am immersed in a project using React. The main goal right now is to dynamically generate a PDF file (invoice) and then securely upload it to Google Drive. In the snippet of code provided below, you can see how I attempted to create the PDF f ...

The dirtyVertices feature in Three.js seems to be malfunctioning

In my three.js project, I created a 12*12 plane and attempted to modify its vertices between two renderings without success. Despite adding the following code, no changes were observed: ground.geometry.dynamic = true; ground.geometry.__dirtyVertices = tr ...

Issues with the audio on ExpressJS video streaming can be quite vexing

After multiple attempts to run an ExpressJS web server that serves videos from my filesystem, I've encountered a frustrating issue. Whenever a video is played, there are constant popping sounds and eventually the audio cuts out completely after 3-10 m ...

What is the best way to determine the size of the URLs for images stored in an array using JavaScript?

I am working on a project where I need to surround an image with a specific sized 'div' based on the image's dimensions. The images that will be used are stored in an array and I need to extract the height and width of each image before disp ...

Create a personalized and distinct name following the submission of data into multiple text fields either through Nuxt/Vue or by utilizing pure JavaScript

In my new app, users can register packages and then participate in a ballot session where the package will be assigned to someone else. To make this process smoother, I want each ballot session or box to have a unique Ballot ID attached to it. For example ...

What causes ng-options to return an empty array in AngularJS when using $element.find('option')?

For my project in Angular 1.4, I am utilizing the ngOptions directive to dynamically fill a <select> element with <option> elements based on an object structure like this: {black: '#000000', red: '#FF0000', ...} The implem ...