3

I would like to modify properties of a CSS class directly using knockout 'data-bind', without using JQuery css() method.

I have a component (bootstrap slider) on which I want to set the background color depending on the slider value. On his homepage, the author is doing it by calculating rgb components and then applying them with jquery css() method.

Can I data-bind properties inside a css class with knockout or must I stick with JQuery css ()?

Edit: I want to change the background-color of a part of the component, described in a css class, not the background of the whole component.

3 Answers 3

2

jQuery css set's style properties on the element directly. This is the same as what the style binding does in Knockout: http://knockoutjs.com/documentation/style-binding.html. So, you should be able to use the style binding to accomplish your task.

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

4 Comments

I already tried but the property I want to change is inside a css class in the component stylesheet. Is there any way to select a property inside a class when using the style binding ?
you can't directly edit a class defined in an external file. I don't think that I would necessarily recommend it, but you can add a binding to a style element defined on the page and some overrides to a CSS class. It would be something like: jsfiddle.net/rniemeyer/6VNdE. At least this way any element that used that class would be automatically updated.
Here is an alternative that uses a custom binding handler to keep some of the logic out of the view model: jsfiddle.net/rniemeyer/s4p9m
Very smart to define a custom binding, I am not advanced enough in knockout to come with this kind of idea ! Thx a lot ! I will try this approach as soon as I get back to work on monday !
2

You can use a data-bind similar to this one:

data-bind="style: { background-color: colorRed() ? 'red' : 'black' }"

By changing the value in colorRed(), you can change to color to red or black. It is also possible to use something like this:

data-bind="style: { background-color: myColor() }"

Where myColor() return a hex color.

1 Comment

Yes but how can I tell that the background-color I want to change is class specific ?
1

Be sure to use backgroundColor instead of background-color You can use this:

data-bind="style: { backgroundColor: color }"

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.