Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

167
Visualizações
Background Color Change Switch Not Working

I'm trying to make a dark/light theme. When I click to flip into light, the function runs. but darken(); seems to be ignored. Am I missing something? no error messages.

<label class="switch">
    <input type="checkbox">
<span class="slider round" onclick="contrast();"></span>
var m = 1

function lightup() {
    document.getElementById('header-wrap').style.backgroundColor = "white"
}

function darken() {
    document.getElementById('header-wrap').style.backgroundColor = 'black'
}

function contrast() {
    if (m = 1) {
        m = 2
        lightup();
    }
    else if (m = 2) {
        m = 1
        darken();
    }
}

contrast(); and lightup(); both fire as intended. darken(); does not.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Value comparison should be done using m === 1 or m == 1. m = 1 is assignment operator

Working Fiddle

var m = 1

function lightup() {
    document.getElementById('header-wrap').style.backgroundColor = "white"
}

function darken() {
    document.getElementById('header-wrap').style.backgroundColor = 'black'
}

function contrast() {
    if (m === 1) {
        m = 2
        lightup();
    }
    else if (m === 2) {
        m = 1
        darken();
    }
}
#header-wrap {
    width: 200px;
    height: 200px;
    border: 1px solid red;
}
<div id="header-wrap"></div>
<label class="switch">
    <input type="checkbox">
    <span class="slider round" onclick="contrast();">Change</span>
</label>

A better apprach is to make the function trigger on the change event of checkbox. Check the checked status of the checkbox and toggle the background color.

Working Fiddle

const checkbox = document.getElementById('checkbox');
const element = document.getElementById('header-wrap');

function contrast() {
    element.style.backgroundColor = checkbox.checked ? "white" : 'black';
}
#header-wrap {
    width: 200px;
    height: 200px;
    border: 1px solid red;
}
<div id="header-wrap"></div>
<label class="switch">
    <input type="checkbox" id="checkbox" onchange="contrast();">
    <span class="slider round">Change</span>
</label>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda