Kiddy
Kiddy

Reputation: 139

Switch between black and white background

Aim: switch background color between black and white by clicking one button.

The following is my code, which does not work.

<html>
<body id="pageBody">
<style>
body {background: #000000; color: #FFFFFF;}
</style>
<p>A sentence.</p>
<button type="button" onclick="changeBG()">Change BG</button>
<script>
function changeBG() {
    var bg = document.getElementById("pageBody");
    if (bg.style.backgroundColor=="#000000") {
        bg.style.backgroundColor="#FFFFFF";
        bg.style.color="#000000";
    }
    else {
        bg.style.backgroundColor="#000000";
        bg.style.color="#FFFFFF";
    }
}
</script>
</body>
</html>

Upvotes: 0

Views: 1102

Answers (2)

Oriol
Oriol

Reputation: 287960

Use classes to make the code more reusable, and to avoid dealing with browsers changing color mode:

body {background: #000; color: #fff;}
body.bg {background: #fff; color: #000;}
document.body.classList.toggle('bg');

If you want it to work on old browsers that don't support classList, then use (assuming body doesn't have other classes):

document.body.className = document.body.className ? 'bg' : '';

Upvotes: 2

SeanCannon
SeanCannon

Reputation: 77956

You're comparing against a hex string - the browser will return RGB values

"rgb(0, 0, 0)" for black and "rgb(255, 255, 255)" for white.

This will work:

function changeBG() {
    var bg = document.body;
    if (bg.style.backgroundColor=="rgb(0, 0, 0)") {
        bg.style.backgroundColor="#FFFFFF";
        bg.style.color="#000000";
    }
    else {
        bg.style.backgroundColor="#000000";
        bg.style.color="#FFFFFF";
    }
}

Working demo: http://jsfiddle.net/FTSYF/

Upvotes: 2

Related Questions