KnockoutJS - CSS Binding



This binding allows you to define CSS classes for the HTML DOM elements based on certain condition. This is useful in case you need to highlight some data depending on a situation.

Syntax

css: <binding-object>

Parameters

  • In case of static CSS binding, the parameter can be in the form of JavaScript Object, consisting of property and its value.

    • Property here refers to CSS class to be applied and value can be Boolean true, or false, or JavaScript expression or a function.

    • Classes can be also applied dynamically using Computed Observable functions.

  • Multiple CSS classes can also be applied at once. Following is an example of how 2 classes are added to binding.

<div data-bind = "css: { 
   outOfStock : productStock() === 0, 
   discountAvailable: discount 
}">
  • Class names can also be specified in single quotes such as 'discount Available'.

  • 0 and null are treated as false value. Numbers and other objects are treated as true value.

  • If the ViewModel property is an observable, then CSS classes are decided depending on the new updated parameter value. If it is not an observable value, then classes are determined only once for the first time.

Example

Let us take a look at the following example which demonstrates the use of CSS binding.

<!DOCTYPE html>
   <head>
      <title>KnockoutJS CSS binding</title>
      <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
         type = "text/javascript"></script>
      
      <style>
         .outOfStock {
            color: red;
            font-weight: bold;
         }
      </style>
      
   </head>
   
   <body>
      <div data-bind = "css: { outOfStock : productStock() === 0 }">
         Product Details.
      </div>

      <script>
         function AppViewModel() {
            this.productStock = ko.observable(0);
         }
         
         var vm = new AppViewModel();
         ko.applyBindings(vm);
      </script>
      
   </body>
</html>

Output

Let's carry out the following steps to see how the above code works −

  • Save the above code in css-bind.htm file.

  • Open this HTML file in a browser.

  • Product Information is shown in a normal way when the productStockproperty is above 0. Product Information becomes red and bold. once productStock becomes 0.

knockoutjs_declarative_bindings.htm
Advertisements