KnockoutJS - Style Binding



Style Binding allows you to apply inline styling to HTML DOM element by manipulating the element's style attribute instead of applying CSS classes. This binding requires key-value pair due to inline styling.

Syntax

style: <binding-object>

Parameters

  • JavaScript object should be passed as a parameter in which the property name refers to style attribute and values refer to the desired values to be applied on the elements.

  • Multiple styles can also be applied at once. Suppose you have a discount property in your ViewModel and you want to add that, then the code will look like the following −

<div data-bind = "style: { 
   color: productStock() < 0 ? 'red' : 'blue', 
   fontWeight: discount() ? 'bold' : 'normal' 
}>

If the productStock is not available, then the font becomes red. Else, it becomes blue. If the discount is set to true, then Product Details will become bold font. Else, it will remain in normal font.

  • If the ViewModel property is observable, then styles are applied depending on the new updated parameter value. If it is not an observable value, then style is applied only once for the first time.

Example

Let us take a look at the following example which demonstrates the use of style Binding.

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

      <script type = "text/javascript">
         function AppViewModel() {
            this.productStock = ko.observable(30000) // initially black as positive value
            this.productStock(-10);                  // now changes DIV's contents to red
         };
         
         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 style-bind.htm file.

  • Open this HTML file in a browser.

  • If productStock goes below 0, then Product Details becomes red. Else, if stock is available it becomes black.

Observations

Illegal Javascript variable names

CSS style name font-weight is not allowed in JavaScript. Instead, write it like fontWeight (Hyphen in variable names is not allowed in JavaScript).

Click here for all JavaScript style attributes, which are also available at KO's official site.

knockoutjs_declarative_bindings.htm
Advertisements