DEV Community

Bram Adams
Bram Adams

Posted on

Quick Tip! Adding Elements to your DOM dynamically

I was playing around with p5.js and blizard.js yesterday, trying to create a fun meme project.

I wanted the screen to go wild a few seconds into it running, and add divs all over the place.

Here is the final result (!!headphones warning!!)

This is the code I ended up with:

function goCrazy () {
    hideAll()
    const downTypes = ["down", "DOWN", "dOwN", "dwn"] //[1]
    const upTypes = ["up", "DOWN", "uP", "upp", "UP"]
    const fontSizes = ['16pt', '24pt', '32pt', '8pt', '72pt']
    const colors = ["black", "white", "red"]
    const colorsUp = ["green", "blue", "magenta"]

    for (let i = 0; i < 50; i++) {
        setTimeout(() => { // [2]
            let downer = document.createElement("p")
            downer.innerText = downTypes[floor(random() * downTypes.length)]
            downer.style=`font-size: ${fontSizes[floor(random() * fontSizes.length)]}; position: absolute; left: ${floor(random() * 1000)}px; top: ${floor(random() * 600)}px; color: ${colors[floor(random() * colors.length)]}` //[3]
            document.body.appendChild(downer)
        }, i*100)
        setTimeout(() => {
            let upper = document.createElement("p")
            upper.innerText = upTypes[floor(random() * upTypes.length)]
            upper.style=`font-size: ${fontSizes[floor(random() * fontSizes.length)]}; position: absolute; left: ${floor(random() * 1000)}px; top: ${floor(random() * 600)}px; color: ${colorsUp[floor(random() * colorsUp.length)]}`
            document.body.appendChild(upper)
        }, i*100)

    }
}
Enter fullscreen mode Exit fullscreen mode

[1] - I used arrays to pick from a selection of choices at random
[2] - You can use let (not var!) to successfully use setTimeout in a regular for loop. This Stack Overflow answer explains it well
[3] - I struggled with CSS class attaching and ended up creating generated inline styles. I'm not sure how well this scales but it worked for me.

Top comments (0)