Introduction:

In this article we will learn how to use CSS binding in KnockoutJS or what is CSS binding in KnockoutJS or why use CSS binding in KnockoutJS with example.

Description:

knockoutJS CSS binding basically used to add or remove a css class from an element. CSS binding are particularly helpful when you want to change the style of an element depending on condition.

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

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="KnockoutJSCSSBinding.aspx.cs"

 

Inherits="AspDotNet.KnockoutJS_CSS_Bindings" %>

 

<!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>

 

    <style>

      .eligible {

      color: red;

      font-weight: bold;

      }

   </style>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    Check Your Age :<input type="text" data-bind="value: Age" />

        <div data-bind="visible: Age() < 18">

              <div data-bind="css: { eligible: Age() < 18 }">

               your age is not eligible for vote.

               </div>

         </div>

 

   <script>

       function VoteModel() {

           this.Age = ko.observable(0);

       }

       var vm = new VoteModel();

       ko.applyBindings(vm);

   </script>

    </div>

    </form>

</body>

</html>


Output:


How to use CSS binding in KnockoutJS


The above code. First go to the header section, here we have defined style. We have specify a class which changes the color of the text to bold and change its color. The name of the class is the “eligible”. Here inside the div we use data-bind attribute to set the css of the div to “eligible” if the use entered Age less than 18 in textbox. Notice the synax for css binding. It is similar to JavaScript object notation where the first parameter is the name object and second parameter is its value. The second parameter in this case is the expression. If this expression returns true, the “eligible” class will be applied to the div.

 I hope this article will help to you.

0 comments


Leave a comment

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

You may also like