Dear All
I have this code ->
if("serviceWorker" in navigator){
navigator.serviceWorker.register("/service.js");}
if(localStorage.getItem("preferredTheme")==="dark"){setDarkMode(true);}
function setDarkMode(isDark){var darkBtn=document.getElementById("darkBtn");
var lightBtn=document.getElementById("lightBtn");
if(isDark){lightBtn.style.display="block";
darkBtn.style.display="none";
localStorage.setItem("preferredTheme","dark");}else{lightBtn.style.display="none";
darkBtn.style.display="block";
localStorage.removeItem("preferredTheme");}
document.body.classList.toggle("darkmode");}
document.getElementById("darkBtn").addEventListener("click", function(){setDarkMode(true);});
document.getElementById("lightBtn").addEventListener("click", function(){setDarkMode(false);});
And I got this warning from LightHouse ->
TypeError: Cannot read property 'addEventListener' of null at https://angora.me/script.js :13:35
Any suggestion how to fix it?
Regards
Top comments (8)
This should happen when there is no element with id 'darkBtn' in document. And this may happen because with condition in above code, the display of darkBtn is none.
I hope this helps you resolve this err.
The fact that an element is not displayed wouldn't stop you from adding an event listener: the element itselt still exists in the DOM. The most likely answer is that for some reason the element doesn't actually exist.
Thats what I said earler.. you disagreed there lol funny😁😁😅. Making conclusion here..
We'd need to see the corresponding HTML and any other code that interacts with the page. The error you get suggests the element doesn't exist. Perhaps you add (or even remove) it dynamically elsewhere? Maybe there's a typo in your id?
Also a suggestion: when posting code snippets put 'js' after the backticks to add syntax highlighting. It makes it much easier to read:
I'm not a javascript developer but it is said here that
In other words for example:
would give you a TypeError because you can't add a string and an integer.
I think the problem is the id (darkBtn and lightBtn) is missing from home page and only exist on inner page. So, I added the id to home page too, and all fixed. Thanks for all your suggestion here. It really helps a lot.
webpagetest.org/result/190929_8W_f...
I think event listener isn't able to find an element with given Id. Make sure you put exact element Id as you defined in your html🤔
If that would have been the case then err would come at line #5. So this is not the case. The condition is making display = none and so the err is coming at line #13.
Some comments may only be visible to logged-in visitors. Sign in to view all comments.