How can I change background color with jQuery .click(function(){
div normal with Green color, when clicked change to red background color
<div class="stileone">
Div Content
</div>
How can I change background color with jQuery .click(function(){
div normal with Green color, when clicked change to red background color
<div class="stileone">
Div Content
</div>
$(".stileone").on("click", function() {
$(this).css("background", "red");
})
DEMO
I know there are plenty answers here, but i thought I would point out, there are many ways to accomplish this and many with slightly different purpose.
Basic CSS Psuedo Classes are meant to handle stuff like this however, they are not always cross-browser compatible. For Instance, I don't think the following works in IE >=8, but it works in Chrome and IE9.
div:active { background-color: red; }
Then of course basic click to css change. This of course will make the change perminant though, without any other commands.
$("div").on("click", function() {
$(this).css("background-color", "red");
});
// OR
$("div").on("click", function() {
$(this).css({ backgroundColor: "red" });
});
As shown earlier in answer, there is click to toggle class. In this case you create a class with your background desired and then toggle that class on and off based on click actions.
$("div").on("click", function() {
$(this).toggleClass('back-red');
});
If you need a jQuery way to immitate
:active
, then you can make use of mousedown/up instead of simple click. This will allow you to effectivly "cross-browser" immitate the ':active` feature of CSS.
$("#div5").on("mousedown", function() {
$(this).toggleClass('back-red');
})
.on("mouseup", function(e) {
$(this).toggleClass('back-red');
});
Finally, the last feature way I can think of right now is to use a method that is currently broken in the NEWEST jQuery (1.8+), however, in all other jQuery's (1.72-) it seems to work fine. It's called the "toggle" method, and is usually used to define aa element showing and hiding. However in older versions it has an alternate feature wherein you can define call backs and thus create your own animations.
$("div").toggle(function() {
$(this).css("background-color", "red");
},
function() {
$(this).css("background-color", "");
});
Work with .on()
. You bind an event on your <div.stileone>
when the event 'click'
occurs, then you reference to your <div.stileone>
object within the function with $(this)
. And toggleClass adds/removes the class every time the Event is triggered.
jQuery:
$('.stileone').on('click',function(){
$(this).css('backgroundColor','red');
// OR: if you want to work with a class
$(this).toggleClass('redClass');
});
css:
.redClass {
background-color: red;
}
you need to find the onclick event to the div, then use
.css("background-color:#00000;);