Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


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
229,788 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).