Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change background color from js

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

like image 567
Federico Rampazzo Avatar asked Jan 30 '23 00:01

Federico Rampazzo


2 Answers

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>
like image 167
prasanth Avatar answered Feb 02 '23 16:02

prasanth


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>
like image 21
Ehsan Avatar answered Feb 02 '23 16:02

Ehsan