I would set the background color of an element by onclick javascript function. My code is:
function changeBg( el ) {
if( $( el ).css( "background-color" ) === "rgb(255,255,0)" ) {
$( el ).css( "background-color", "red" );
}
else {
$( el ).css( "background-color", "rgb(255,255,0)" );
}
}
This code works for change the default background color to yellow (rgb(255, 255,0)) but it doesn't work from yellow to red. The first condition is always skipped
For more better way use with toggleClass()
instead of color value matching with in dom
function changeBg(el) {
$(el).toggleClass('red')
}
.red {
background-color: red;
}
button{
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="changeBg(this)">change</button>
Try This:
$(document).ready(function(){
$('button').click(function(){
$(this).toggleClass('redColor');
})
})
button {
background-color: yellow;
}
.redColor {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button>Click Me!</button>
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