Federico Rampazzo
Federico Rampazzo

Reputation: 73

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

Upvotes: 4

Views: 1243

Answers (3)

Ehsan
Ehsan

Reputation: 12951

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>

Upvotes: 1

Bibhudatta Sahoo
Bibhudatta Sahoo

Reputation: 4894

Try this

$(document).ready(function() {
$('.container').on('click',function(){
  var el = ".container";
  if ($(el).css("background-color") === "rgb(255, 255, 0)") {
    $(el).css("background-color", "red");
  } else {
    $(el).css("background-color", "rgb(255, 255, 0)");
  }
  });
});
.container {
  background-color: rgb(255, 255, 0);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  Test
</div>

Upvotes: 0

prasanth
prasanth

Reputation: 22490

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>

Upvotes: 7

Related Questions