Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading