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?
To set the background-color, we use css() method. This method helps us to add CSS properties dynamically.
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.
Create a CSS class:
.clicked {
background-color: yellow;
}
and then simply toggle that class it via jQuery:
$('.star').click(function(){
$(this).toggleClass('clicked');
});
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With