Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Change color on click

Tags:

jquery

I'm looking at some jQuery because I want to create a div that changes color when you click it.

And I've done that with:

$(function() {  
$('.star').click(function(){
    $(this).css('background', 'yellow');

  });
});

And it works perfectly! But I want it to remove the background color, when you click it one more time. Is that possible, and how would you do something like that?

like image 714
skolind Avatar asked Oct 27 '11 14:10

skolind


People also ask

How to change background color in jQuery dynamically?

To set the background-color, we use css() method. This method helps us to add CSS properties dynamically.

How to change color of button when clicked HTML?

Use HTML DOM Style backgroundColor Property to change the background color after clicking the button. This property is used to set the background-color of an element.


2 Answers

Create a CSS class:

.clicked {
  background-color: yellow;
}

and then simply toggle that class it via jQuery:

$('.star').click(function(){
  $(this).toggleClass('clicked');
});
like image 97
Tomalak Avatar answered Nov 11 '22 23:11

Tomalak


You could set a flag in your click function, Then add an if statement

if hasBeenClicked = true;
//...background color remove
else
//....background color changed to yellow

hasBeenClicked = true;
like image 26
Danielle Stone Avatar answered Nov 11 '22 23:11

Danielle Stone