Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Background color (css property) using Jquery

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>
like image 511
Sanjay B Avatar asked Jan 05 '14 11:01

Sanjay B


People also ask

How can set background color in jQuery?

To set the background color using jQuery, use the jQuery css() property. We will set background color on mouse hover with the jQuery on() method.

How can change background color of button click in jQuery?

To change the background color using jQuery, use the jQuery css() property. We will change background color on mouse hover with the jQuery on() and css() method.

How do I change the background color of all HTML button with class test using jQuery?

click(function(){ var class = $(this). attr("data-class"); var color = $(this). attr("data-color"); $("."+class). css("background-color",color); });


1 Answers

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

like image 131
Sterling Archer Avatar answered Sep 23 '22 11:09

Sterling Archer