4

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

8
  • I would recommend putting the jQuery object in a variable. Rather than creating a new jQuery object on each line. Commented Jul 12, 2017 at 10:27
  • try to capture value, before compare, will be different. Because is parsing to hexadecimal, and your comparation is RGBA Commented Jul 12, 2017 at 10:29
  • I tried to print the typeof and the value of the element background color and return String rgb(255,255,0) Commented Jul 12, 2017 at 10:31
  • 2
    As you're comparing strings, try putting spaces in between the RGB values as that's likely to be the issue $( el ).css( "background-color" ) === "rgb(255, 255, 0)" Commented Jul 12, 2017 at 10:32
  • Are you sure its not returning "rgb(255, 255, 0)" with the spaces Commented Jul 12, 2017 at 10:32

3 Answers 3

7

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>

Sign up to request clarification or add additional context in comments.

1 Comment

inline js / css caused by js needs to stop :D this should be used^^ :)
1

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>

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.