Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

166
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda