Mike
Mike

Reputation: 159

jQuery changing body's background color

This is frustrating and I can't figure this out. I just need to change/toggle back/foreground color for the entire body when user clicks on a link, 'theme'. Following is my html file.

...
<style>
    highlight {
        background-color: black;
        color: white;
    }
</style>
<script>
    $(document).ready(function () {
        $('.theme').on('click', function () {
            $(document.body).toggleClass("highlight");
            //$(document.body).css({"background-color": "black"});
        });
    });
</script>

When I use $().css({...}), it works but when I try to use class to be able to toggle, it doesn't. Please help.

Upvotes: 1

Views: 1492

Answers (3)

Mohini Jamdade
Mohini Jamdade

Reputation: 488

This will work

HTML

<a href="#" id="theme">Click Me</a>

CSS

body { background-color:red; }
.highlight
 {
  background-color:yellow;  
 }

JQUERY

$("#theme").click(function() {
$("body").toggleClass("highlight");

});

Here is the working code http://jsfiddle.net/CLwE5/119/

Upvotes: 1

kong.fu
kong.fu

Reputation: 64

Agree with Rayon. "highlight" in the style is not a class if missing the period in front. jQuery is not able to toggle the "highlight" class since there's no "highlight" class to toggle. The code works here: http://liveweave.com/T6c7Mz

Upvotes: 1

alamnaryab
alamnaryab

Reputation: 1484

change the following line

$(document.body).toggleClass("highlight");

with

$("body").toggleClass("highlight");

Upvotes: 1

Related Questions