I’m getting an uncaught type error in my console when I click my button, I was wondering why this is happening? It says null but I thought its pointing to my button with id button. Kudos to anyone who can shed some light on what I am doing wrong
ERROR:
main.js:22 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
at main.js:22:5
(anonymous) @ main.js:22
HTML:
<!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>Document</title>
<link rel="stylesheet" href="main.css">
<script src="main.js"></script>
</head>
<body>
<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>
JS:
var hexDisplay = document.getElementById("hex-display");
function colorFlipper() {
var chars = "0123456789ABCDEF"; // Defining HEX Characters
var result = ""; // Having an empty string to store the result
for (var i=0; i<6; i++) { // A loop, that runs until i is smaller than 6, so.. 6 times
var num = Math.floor(Math.random() * chars.length); // It defines a variable num, which generates a random number between 0 and the length of our HEX Characters string
result += chars.substring(num,num+1); // The result then takes that number and the next one, and extracts a character in our HEX Character string that is in between those 2 numbers
}
hexDisplay.textContent = "#" + result; // Then we display the result and set the background color
document.body.style.backgroundColor = "#" + result;
}
CSS:
@import url('https://fonts.googleapis.com/css2?family=Ranchers&display=swap');
main {
min-height: calc(100vh - 3rem);
display: grid;
place-items: center;
}
.container {
text-align: center;
}
.container h2 {
background: #222;
color: #fff;
padding: 1rem;
border-radius: 0.25rem;
margin-bottom: 2.5rem;
}
.color {
color: hsl(205, 78%, 60%);
}
.btn-hero {
font-family: "Ranchers", sans-serif;
text-transform: uppercase;
background: transparent;
color: #222;
letter-spacing: 0.1rem;
display: inline-block;
font-weight: 700;
transition: all 0.3s linear;
border: 2px solid #222;
cursor: pointer;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
border-radius: 0.25rem;
font-size: 1rem;
padding: 0.75rem 1.25rem;
}
.btn-hero:hover {
color: #fff;
background: #222;
}
I’ve tried googling and searching through the code and can’t find what is wrong