Search code examples
javascripttextrandom

How to make matrix like text change effect in javascript?


I was trying to make this text change matrix movie like effect in JavaScript.The basic concept was that there is a div present in html and JavaScript take that div's inner text and manipulate it to create the continuously changing random text effect like in matrix movie. I am quite new to JavaScript, I am having hard time figuring out the logic behind the animation like the each steps, one step after another like what will happen next in whole animation process.

Anyways, I tried to make it on my own but as you can suspect i failed.

Here is my code :

<html>
<head>
    <script>

        var text = document.getElementById("text").innerText;
        var length_var = text.length;
        var possible = [];
        var possible_text ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        var counter = 0;
        var arr_text = [];

        var new_func = function(){
            arr_text[Math.floor(Math.random() * length_var)] = possible.charAt(Math.floor(Math.random() * possible.length));
            alert(arr_text);

        };

        var call_func = function(){

            for(var i=0; i<=possible_text.length; i++){
                possible[i] = possible_text.charAt(i);
            }

            for(var i=0; i<= length_var ; i++){
                arr_text[i] = text.charAt(i);
            }

            setInterval(new_func, 100);

        };

    </script>
</head>
<body onload="call_func()">

    <div id="text">
        Hello There!
    </div>
</body>
</html>

What I was planning to do can be seen on this page, as I was highly motivated to do this effect on my own.

Link : http://events.ccc.de/congress/2012/wiki/Main_Page

The header text of the page contains such animation.

Please Help


Solution

  • This changes the string sequentially.

    function main() {
        "use strict";
        var counter = 0, all = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        var $_inter = setInterval(function() {
            var text = document.getElementById("text");
            text.innerHTML = text.innerHTML.substring(0, counter) + all.charAt(Math.floor(Math.random()*all.length)) + text.innerHTML.substring(counter+1);
            counter = (counter+1)%text.innerHTML.length;
        }, 100);
    }
    window.onload = main;