Home > Back-end >  Javascript code block not working with other page
Javascript code block not working with other page

Time:08-29

I have some problem with my JavaScript code that I need help from you

index.html

<body>
   <button >Dark</button>
   <p>First Page</p>
</body>

second-page.html

<body>
   <p>Second Page</p>
</body>

main.css

root{
  --bg-color: white;
}

.dark{
   --bg-color: black;
}

body{
   background-color: var(--bg-color);
}

main.js

const btn = document.getElementById('dark')
const body = document.body

btn.addEventListener('click',function (){
  body.classList.toggle('dark')
  if(body.classList.contains("dark")){
    localStorage.setItem("mode","dark")
  }
  else{
    localStorage.setItem("mode","light")
  }
});

if(localStorage.getItem('mode') == "dark"){
  body.classList.toggle('dark')
};

All of my Html page I was link with the same javascript page but my index.html is working normal but my Second page(seceond-page.html) is not working, because in this page there is no class name "dark".
and I also have some solve but that not logic and I need more code block for my html page from that file.

My solve is Change line that define a variable

const body = document.body;

if (localStorage.getItem('mode') == 'dark') {
  body.classList.toggle('dark');
}

const toggleMode = document.querySelector('.theme-icon');
toggleMode.addEventListener('click', function () {
  body.classList.toggle('dark');
  if (body.classList.contains('dark')) {
    localStorage.setItem('mode', 'dark');
  } else {
    localStorage.setItem('mode', 'light');
  }
});

CodePudding user response:

You can wrap your btn variable usage in an if condition before doing anything with it;

if(btn){
    btn.addEventListener('click',function(){});
}

This way, if the #dark element doesn't exist, the code wont run.

Also, your way of making a dark mode logic is a bit flawed. It can be made very simple. Like https://dev.to/codedgar/how-to-create-a-dark-theme-system-in-5-minutes-or-less-with-vanilla-js-2922

CodePudding user response:

I see the plan for two modes, of them I like light.

Be dresed in white always... index.html:

 <button id="toggle"></button>

second.html:

 <p></p>

site.js:

     //for two of pages, when they are loading, if js enabled!
     try{
         document.body.style.backgroundColor=localStorage.local
        } catch {}
     var local;
 
   
 toggle.setAttribute('onclick','local=document.body.style.backgroundColor=document.body.style.backgroundColor==`black`?`white`:`black`');
     try{
         localStorage.setItem('local',local);
        } catch {}
  • Related