Search code examples
javascriptknockout.jsknockout-3.0

KnockoutJS css and class in the same binding


Despite the section in https://knockoutjs.com/documentation/css-binding.html i wasnt able to use css and class together, instead I could use two different css bindings: http://jsfiddle.net/g9sot5qb/

Am I doing something wrong or is the documentation inaccurate?

<span class="cls1 cls2" data-bind="text: title,css: {active: active}, class: myClass" ></span>
<span class="cls1 cls2" data-bind="text: title,css: {active: active}, css: myClass" ></span>

Solution

  • The class binding is a Knockout version 3.5 feature.

    From the v 3.5 release notes:

    The new class binding supports dynamic class strings.
    This allows you to use the css and class bindings together to support both methods of setting CSS classes.


    Your jsfiddle is using an older version.

    Also note that the observable active must have a true value in order to get the css class 'active' applied.

    See the (runnable) example below, where both a class and css binding are active.

    var viewModel= {
      myClass: ko.observable('test'),
      title: ko.observable('Title'),
      active: ko.observable(true)
    };
    
    ko.applyBindings(viewModel);
    .test{
      color: red
    }
    
    .active {
      font-size: 32px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-min.js"></script>
    
    <span class="cls1 cls2" data-bind="text: title, css: {active: active}, class: myClass" ></span>