0

On button press, I want to change the color and background color of a button based on whether or not is "checked" which I'm currently checking by reading the current color.

Currently, it doesn't seem like the CSS value that is being read by jQuery is being updated by the function that jQuery uses to update the CSS.

Here's a JSFiddle that demonstrates the issue.

JSFiddle

function toggleButton(button) {
  let css = {
    "checked": {
      "background-color": "#609",
      "color": "#fff"
    },
    "unchecked": {
      "background-color": "#ccc",
      "color": "#222"
    }
  }
  button.css("color", "#222") ?
    button.css(css.checked) :
    button.css(css.unchecked)
}
button {
  background-color: #ccc;
  color: #222;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="toggleButton($(this))">Click me</button>

3
  • 1
    This button.css("color", "#222") does not magically check the current color value against "#222" and returns true/false: .css() Commented Mar 10, 2017 at 17:22
  • Based on what @Andreas said, that isn't the right way to check the color of an element: jsfiddle.net/3197r2yf/1 Commented Mar 10, 2017 at 17:23
  • @Andreas Wow I feel stupid. Not sure how I ended up thinking that's what it was doing. Thanks. Commented Mar 10, 2017 at 18:59

1 Answer 1

1

Your first problem is that you're using the setter of css() in your if condition. As this returns a jQuery object it will always equate to true.

The second problem is that even when corrected (button.css('color') == '#222') the css() method will return the color in RGB format, so comparing it to the hex value will always be false.

To fix the problem, toggle a class on the element instead. It would also be much better practice to use an unobtrusive event handler instead of the outdated on* event handler. This has the added benefit of de-coupling the CSS and JS code. Try this:

$('button').click(function() {
  $(this).toggleClass('foo');
});
button {
  background-color: #ccc;
  color: #222;
}

button.foo {
  background-color: #609;
  color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click me</button>

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

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.