3
4 Comments

Need Help About JavaScript Error Log

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

on September 28, 2019
  1. 2

    if you remove the "document.body.classList.toggle("darkmode")" it will work. cuz it will basically remove it from dom. I dont understand really what is going on inside ur code. but try remove that line and see if it works. If it works, find an other way to do the modifcations, or just place that line right after adding eventlistens

  2. 2

    The element with id #darkBtn is missing from your dom.
    (lightBtn is missing too)

  3. 1

    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.

    http://webpagetest.org/result/190929_8W_faafdb08c8b78e2d0a149b6b190f4dd3/

    Thanks, @YamiMiami, @macris, @philipimperato.