I checked all the files if their names does not match but I find no problems at all. While I am trying to solve this i came across a video. He write 'defer' between the script tag and I tried to do so too and it worked. But I have no idea why. If someone can explain me why my js not worked before and work after the defer, I would be really appreciated. Here are my html and js codes: This one's js is working because it has defer in script tag
<!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" />
<title>Color Flipper || Simple</title>
<link rel="stylesheet" href="styles.css" />
<script src="app.js" defer></script>
</head>
<body>
<nav>
<div class="nac-center">
<h4>Color Flipper</h4>
<ul>
<li><a href="index.html">simple</a></li>
<li><a href="hex.html">hex</a></li>
</ul>
</div>
</nav>
<main>
<div class="container">
<h2>Background color : <span class="color"> #f1f5f8 </span></h2>
<button class="btn btn-hero" id="btn">Click Me</button>
</div>
</main>
</body>
</html>
This one's js does not work because theres no defer in script tag
<!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" />
<title>Color Flipper || Simple</title>
<link rel="stylesheet" href="styles.css" />
<script src="app.js" ></script>
</head>
<body>
<nav>
<div class="nac-center">
<h4>Color Flipper</h4>
<ul>
<li><a href="index.html">simple</a></li>
<li><a href="hex.html">hex</a></li>
</ul>
</div>
</nav>
<main>
<div class="container">
<h2>Background color : <span class="color"> #f1f5f8 </span></h2>
<button class="btn btn-hero" id="btn">Click Me</button>
</div>
</main>
</body>
</html>
const colors = ["green", "red", "rgba(133,122,200)", "#f15025"];
const btn = document.getElementById("btn");
const color = document.querySelector(".color");
// background color changer
btn.addEventListener("click", function () {
// get random number between 0 and 3 because we got an array that has 4 items
const randomNumber = 2;
document.body.style.backgroundColor = colors[randomNumber];
color.textContent = colors[randomNumber];
});
PS: I am a beginner so if my question is silly, dont go hard on me please :)
`
– SIMBIOSIS surl Aug 23 '21 at 12:34