Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


Leo Effert
Leo Effert
3,704 Points

I'm building a website that looks like it's reading code from the Matrix

Below is part of my code. I actually have 30 paragraphs. How can I get a similar result without writing every single paragraph? And how can I make the page update automatically ever 0.5 second or so?

html: <p id="p1"></p><p id="p2"></p><p id="p3"></p><p id="p4"></p><p id="p5"></p>

css: body { background-color: black; } p { display: inline-block; float: left; color: green; margin-right: 10px; }

javascript: var showNumber = Math.floor(Math.random() * 10); var allNumbers = 100; document.getElementById("p1"); document.getElementById("p2"); document.getElementById("p3"); document.getElementById("p4"); document.getElementById("p5"); while (allNumbers > 0) { p1.innerHTML = p1.innerHTML + "<br>" + showNumber; showNumber = Math.floor(Math.random() * 10); p2.innerHTML = p2.innerHTML + "<br>" + showNumber; showNumber = Math.floor(Math.random() * 10); p3.innerHTML = p3.innerHTML + "<br>" + showNumber; showNumber = Math.floor(Math.random() * 10); p4.innerHTML = p4.innerHTML + "<br>" + showNumber; showNumber = Math.floor(Math.random() * 10); p5.innerHTML = p5.innerHTML + "<br>" + showNumber; showNumber = Math.floor(Math.random() * 10); allNumbers = allNumbers - 1; showNumber = Math.floor(Math.random() * 10); }

1 Answer

Steven Parker
Steven Parker
221,291 Points

Don't forget to assign your paragraph variables. You might not have realized this was missing because most browsers will do this for you for legacy reasons, but it should not be counted on:

var p1 = document.getElementById("p1");  /*
^^^^^^^^   assign variable!              */

You can also save a lot of repeated code by creating a function to return a random digit, and calling it in the loop.

I'm not sure what you have in mind "without writing every single paragraph". but instead re-writing the entire paragraph you might remove the first digit (and line break) and and another one to the end.

Finally, if you wrap the entire loop in a function, you could use "setInterval" to call that function every ½ second (500 ms).