0

I was practicing my js since ima beginner and was trying to make a program to change the background color but whenever I was trying to use dom-manipulation nothing happened if anybody knows why that happens I would be very thankful.

HTML source:

<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="app.js"></script>
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class="button-style">
    <button class="button">Click me!</button>
</div>

</body>
</html>

CSS code:

body{
background-color: red;
}

.button{
background:transparent;
}

Js script:

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]
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
VVV
  • 1
  • 2
  • Because your ` – Dai Feb 23 '22 at 09:59
  • First off: Nice work, because the code **does** work correctly when you include the script correctly. :-) Whenever you're doing browser-based development, be sure to have the devtools console open (or at least open it when things don't work). In this case, you'd have gotten an error about trying to use `addEventListener` on `null`, because `button` is `null` when you go to do that, because of [this issue](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) (covered in the other questions' answers as well). – T.J. Crowder Feb 23 '22 at 10:03
  • Thank you all so much i have now fixed my issue! – VVV Feb 25 '22 at 12:39

0 Answers0