Changing background color from js

I would set the background color of the element with the javascript onclick function. My code:

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 changing 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

+3


source to share


3 answers


For more efficient use use toggleClass()

instead of a color value that matches the 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>
      

Run codeHide result


+7


source


Try the following:



$(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>
      

Run codeHide result


+1


source


try it

$(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>
      

Run codeHide result


0


source







All Articles