Confusion about how to use DOM correctly in JS

So I’m trying to make a page with a single button that changes the background colour of the page but when I click the button nothing happens. And I don’t know what I’ve done wrong? Any help would be appreciated!

Regards
Ma3_str0

My JS and HTML code:

const colorArray = ['blue','red','orange','green','yellow','black'];

function changeColors(){

    document.body.style.backgroundColor = colorArray[Math.floor(Math.random() * colorArray.length)];

}

document.getElementById("click-button").onclick = changeColors();
<!DOCTYPE html>
<html>

    <head>
        <title>Change the background color!</title>

        <script src="app.js"></script>

        <style>
            #title{
                background-color: cadetblue;
                text-align: center;
                text-decoration: underline;
                color: coral;
                padding: 10px;
                
            }
            #centering{
                margin-top: 250px;
                text-align: center;
            }
            #click-button{
                padding: 25px;
                font-size: 20px;
            }
        </style>
    </head>
    <body>
        <h1 id="title">Change the background color of the page!</h1>
        <div id="centering">
            <button id="click-button">Click Me!</button>
        </div>
    </body>

</html>

You’re setting the onclick handler for the button in the JS. Try setting it in the HTML instead, like this. I added onclick="changeColors()" to the button tag, and commented out the last line of your JS.

It’s helpful for you to look at the button itself in the HTML and see immediately what function it’s setting off, rather than wondering if you had done some scripting with that button and then trying to find it in the JS. Hopefully that makes sense :slight_smile:

1 Like

What happens when you comment #const colorArray or you remove it?

Thanks it works! I’ll rather use the attribute in the button tag in the future rather than trying to do it in JS. Thanks again for the help!

1 Like

you can use event listeners
try looking at those, instead of using onclick, to learn a different way of doing it

  1. You are running the function, you need to pass the function to onclick as a callback.

document.getElementById("click-button").onclick = changeColors;

  1. Using addEventListener is preferable (Why use addEventListener()?).

The reverse is just as true.

Using an inline handler you can’t see if it is attached to an element, or what element it is attached to, from inside the JavaScript.

I think any benefit of having inline event handlers are quickly overshadowed by the downsides. Personally, I would not recommend using inline handlers.

1 Like