Change Background color (css property) using Jquery

11

I want to Change the background colour on click . This is my code work that i tried.pls help me out :)

   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">

$(document).ready(function(){

$(#co).click(change()
{
$(body).css("background-color":"blue");
});
}); 

Css code

body
{
background-color:red;
}

Body code

      <body>

    <div id="co" click="change()">

hello

    </div>

This question is tagged with javascript jquery html css

~ Asked on 2014-01-05 11:05:18

The Best Answer is


25

You're using a colon instead of a comma. Try:

$(body).css("background-color","blue");

You also need to wrap the id in quotes or it will look for a variable called #co

$("#co").click(change()

There are many more issues here. click isn't an HTML attribute. You want onclick (which is redundant). Try this:

<div id="co"> <!-- no onclick method needed -->
<script>
$(document).ready(function() {
    $("#co").click(function() {
        $("body").css("background-color","blue"); //edit, body must be in quotes!
    });
});
</script>

You were trying to call an undefined method. It looks like you were trying to declare it inside the callback statement? I'm not sure. But please compare this to your code and see the differences.

http://jsfiddle.net/CLwE5/ demo fiddle

~ Answered on 2014-01-05 11:06:20


4

Try this

$("body").css({"background-color":"blue"}); 

~ Answered on 2014-09-06 05:28:03


Most Viewed Questions: