Reputation: 9278
I have the following JS:
$(".place").mouseover(function () {
$(this).css('background-color', '#00cc00'); // green color
}).mouseout(function () {
$(this).css('background-color', '#336699'); // light blue color
});
When mouse is over then div become green. I want when user clicks on div then div persist green color. If they click again then set color to light blue. How can I do this?
Thanks.
Upvotes: 4
Views: 61095
Reputation: 78971
Use .toggleClass()
function instead.
Usage:
$(".place").click(function () {
$(this).toggleClass("green");
});
Initially give background-color: #336699
and override this style later on with the toggleClass()
.
Your CSS should look something like this.
.place { background-color: #336699; }
.place:hover, .place.green { background-color: #00cc00; }
See this in action here.
Update 1: Demo with the green in hover .
Upvotes: 33
Reputation: 573
The easiest way to do this would be a toggle, perhaps using a class like this:
$(".place").click(function () {
$(this).toggleClass('green-bg');
});
Have it light blue by default, then on click it would toggle the "green-bg" class which would of course apply the green background.
You might have some issues with toggling both on hover and on click, I'm not sure what you want the priority to be as to what action takes precedent in assigning the bg color.
Upvotes: 3
Reputation: 298166
Use CSS for the hover, not jQuery:
.place {
background-color: #336699;
}
.place:hover {
background-color: #00cc00;
}
And as @Starx pointed out, use .click()
.
Upvotes: 2
Reputation: 1919
$(".place").click(function(){
if($(this).css('background-color')=='#00cc00')
$(this).css('background-color', '#336699');
else {
$(this).css('background-color', '#00cc00');
}
});
Upvotes: 4