I’m learning javascript and tried creating a web page where the user can switch between dark and light theme, but the browser returns this error: Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
The problem is that it doesn’t work if I use an external js file, how can I fix it?
const btn = document.querySelector(".btn-toggle");
// Listen for a click on the button
btn.addEventListener("click", function() {
// Then toggle (add/remove) the .dark-theme class to the body
document.body.classList.toggle("dark-theme");
});
body {
--1: #f2f2f2;
--2: #50250a;
--3: #181818;
--4: #ff9100;
--5: #ffb400;
--6: #ff325a;
}
body.dark-theme {
--1: #181818;
--2: #281400;
--3: #f2f2f2;
--4: #ffb400;
--5: #ff9100;
--6: #ff325a;
}
body{
background-color: var(--1);
color: var(--3);
}
a{
color: var(--5);
transition: 0.5s;
}
a:hover{
color: var(--6);
}
<body class="">
<button class="btn-toggle">Toggle Dark Mode</button>
<h1>Title</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce in fringilla lacus. Vestibulum ut libero laoreet, dictum odio sed, posuere elit. Nulla semper tempor augue, lacinia vestibulum urna venenatis et. Phasellus a erat et lectus laoreet dictum vitae id nisi. Nam et eros mauris. Etiam interdum urna quis mattis finibus. Phasellus in lorem dapibus, elementum diam et, sagittis quam. Cras eu erat sapien. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque congue vehicula sem, id sodales libero euismod vel. Cras bibendum, nulla id facilisis sollicitudin, quam ligula imperdiet lacus, sed dapibus eros mi quis arcu.
</p>
</body>
Thanks!
>Solution :
One hypothesis is, your script is executed before the button is created in the DOM. Do you attach the script at the end of your HTML document?
That should work
<!-- ... -->
<body>
<button class="btn-toggle">Click me</button>
</body>
<script>
// script here
</script>
and this shouldn’t:
<script>
// script here
</script>
<body>
<button class="btn-toggle">Click me</button>
</body>