Cammy Gets DOMmed

So the new somnol.net is gonna be the first time I’ve ever properly needed JavaScript on a site. Everything I’ve needed to do up to this point, aside from WordPress, has been totally static HTML and CSS. JavaScript is overrated.

The about section for the new site, however, requires some onClick action to load each bio and therefore I can’t avoid it. Rather than hacking up some example code from StackOverflow like the Indian lancer thinks I am, I’ve actually been scouring MDN, trying my best to learn the correct way to modify the page DOM, as it’s called. Doubly so; I’m gonna eventually need this to fill out Tesserae.

One of the more minor uses of JavaScript on the new somnol.net is randomizing heading banners, banner ads (which will be explained in time, but you can have one potentially >w>), and the sketches of lads on the home page. Now, I’ve been reusing the same randomizer script I hacked up without any JavaScript knowledge for about two years now, but I figured I’d clean it up that I know what was going on a little better.

So here’s the old randomizer script, truncated and with the symbol codes hacked up a little so WordPress didn’t mistake them for actual symbol codes.

var textselect = new Array (); // INCOMING CHEAT SHEET IF YOU WANNA KNOW WHERE I GOT THESE LYRICS
textselect[0] = "Let me come undone in your mouth" // "Undone" by Failure
textselect[1] = "All twisted up in wires" // "Never Get Out" by Brad Sucks
textselect[2] = "Fortunately gone, I wait for you" // "Fortunately Gone" by The Breeders
// …
var r = Math.floor(36*Math.random())
document.getElementById("footer_text").innerHTML = "&\quot;" + textselect[r] + "&\quot;";

Now, this works, but it’s messy. The array is written out longhand and I hardcoded in the amount of items in the array in the Math.floor() function. Plus, I’m not using any IDs in this where I can help it, so I’d need a way to select classes instead. Here’s what I’m using instead:

var banners = ["daf", "garden", "somnol"];
var r = Math.floor(banners.length*Math.random());
document.querySelector(".banner").innerHTML = "<img src='images/banners/" + banners[r] + ".png' alt='Banner'>";

Super basic, but I’m satisfied with it. Basically, all the filenames are stored in the array, and they just get concatenated into the HTML that gets slipped into the markup proper. I get that innerHTML can get your XSS cherry popped, but I still don’t know of a better alternative, and this is my own markup being used, not user input, so I think I’m good.

I’ll have something more impressive to show off soon. Still, neat to be writing code again.

Leave a Comment