• 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.


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">
    <script src="Scripts/jquery-3.1.1.min.js"></script>
    <script src="Scripts/knockout-3.4.2.js"></script>
    <form id="form1" runat="server">
    Check Your Age :<input type="text" data-bind="value: Age,
    style: { 'background-color': Age() < 18 ? 'red' : 'green',color:'white' }" />
       function VoteModel() {
           this.Age = ko.observable(0);
       var vm = new VoteModel();



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.


Leave a comment

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

you may also like