0

I am new to JS. I was trying to make a button which will change the BG color of the HTML page. This is HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="js/index.js"></script>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button class="btn btn-outline-secondary">Click Me!</button>
</body>
</html>

and here is the JS:

const button = document.querySelector('button');
const body = document.querySelector('body');
const colors = ['red', 'green', 'blue', 'yellow', 'pink', 'purple'];

body.style.backgroundColor = 'violet';
button.addEventListener('click', changeBackground);

function changeBackground(){
const colorIndex= parseInt(Math.random()*colors.length);
body.style.backgroundColor = colors[colorIndex];
}

this code is not working and it is constantly giving error on console

index.js:5 Uncaught TypeError: Cannot read property 'style' of null

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

0

Put your script to execute after your body loaded

<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button class="btn btn-outline-secondary">Click Me!</button>
    <script src="js/index.js"></script>
</body>

</html>
EugenSunic
  • 13,162
  • 13
  • 64
  • 86