• Introduction:
      • In this article we will learn how to use Style binding in KnockoutJS or what is Style binding in KnockoutJS or why use Style binding in KnockoutJS with example.

Description:

knockoutJS style binding basically used to add  custom style to DOM element. Style binding are particularly helpful when you want to change the style of the DOM element such as textbox, Div, table etc. We can add style directly or conditional.

Let’s see a simple example of knockoutJS Style binding.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="KnockoutStyleBinding.aspx.cs" 
 Inherits="AspDotNet.KnockoutStyleBinding" %>
<!DOCTYPE html>
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-3.1.1.min.js"></script>
    <script src="Scripts/knockout-3.4.2.js"></script>
 
</head>
<body>
    <form id="form1" runat="server">
    <div>
    Check Your Age :<input type="text" data-bind="value: Age,
    style: { 'background-color': Age() < 18 ? 'red' : 'green',color:'white' }" />
    
   
 
   <script>
       function VoteModel() {
           this.Age = ko.observable(0);
       }
       var vm = new VoteModel();
       ko.applyBindings(vm);
   </script>
    </div>
    </form>
</body>
</html>

 

Output:


How to use Style binding in KnockoutJS


In the above code we have a text box. KnockoutJS style binding is used to set the custom style property of the text box via “Age” attribute of the voteMode of the JavaScript. If you entered the value in text box less than 18 then text box background color shall red but if you entered greater than 18 then text box background color shall green.

 

 I hope this article will help to you.

comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

You may also like