Home > OS >  Change div id on button click function, to create a darkmode
Change div id on button click function, to create a darkmode

Time:11-04

I'm trying to write a JavaScript that makes an id change its id on click. Basically, I would like to create a dark mode toggle button. Not sure what I'm doing wrong though.

HTML

<button id="nottebottone" >Attiva modalità notturna</button>

CSS

#Sito {
    max-width: 1024px;
    margin: auto;
    text-align: center;
    background-color: rgb(221, 241, 235);
    border: black ridge;
    border-width: 0.03cm;
}

Which I'm trying to change to:

#Nightmode {
    max-width: 1024px;
    margin: auto;
    text-align: center;
    background-color: rgb(0, 0, 0);
    border: rgb(255, 255, 255) ridge;
    border-width: 0.03cm;
    color: white;
}

JavaScript:

let bottonedarkmode = document.getElementById("nottebottone");

function attivadarkmode() {
   if (document.div.id == "Sito") {
       document.div.id = "Nightmode";
   }
   else {
       documento.div.id = "Sito";
   }
}

bottonedarkmode.addEventListener('click', attivadarkmode);

Click the button nottebottone to enable the id switch, but nothing happens.

CodePudding user response:

You should do it like this:

let darkModeBtn = document.querySelector(".notte");

function attivadarkmode() {
  darkModeBtn.classList.toggle('light');
  darkModeBtn.classList.toggle('dark');
}

darkModeBtn.addEventListener('click', attivadarkmode);
.notte {
  max-width: 1024px;
  margin: auto;
  text-align: center;
}

.light {
  background-color: rgb(221, 241, 235);
  border: black ridge;
  border-width: 0.03cm;
}

.dark {
  background-color: rgb(0, 0, 0);
  border: rgb(255, 255, 255) ridge;
  border-width: 0.03cm;
  color: white;
}
<button id="nottebottone" >Attiva modalità notturna</button>

At a first glance, I'm assuming the issue is that you typed documento instead of document in the else portion of your function, though I didn't check thouroughly.

CodePudding user response:

I hope this will help you for changing ID:

document.getElementById('nottebottone').id = 'Nightmode';
  • Related