Background Color Change Switch Not Working

Viewed 22

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.

1 Answers

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>

Related