Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a dynamic class in knockoutjs?

Let's say i have,

<span class="cls1 cls2" data-bind="title: title" ></span>

I want to add another class via JSON object,

{ title: 'a', clas: 'cls3' }

This work's,

    <span class="cls1 cls2" data-bind="attr:{title: title,'class': 'cls1 cls2'+clas}" ></span>

But the problem is that it will add two class attributes. I need the cls1 and cls2 class on beginning. But need cls3 class after some event.

like image 394
Imran Qadir Baksh - Baloch Avatar asked Jan 10 '13 10:01

Imran Qadir Baksh - Baloch


People also ask

How do you bind a class in HTML?

Class binding with Class There are another shorthand way to bind CSS Class to HTML element. className is name of the class, which you want to bind to. condition must return true or false. A return value of true adds the class and a false removes the class.

How do I declare a class in CSS?

To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class. To do this, start with the element name, then write the period (.)

Is knockout js easy?

KnockoutJS library provides an easy and clean way to handle complex data-driven interfaces. One can create self-updating UIs for Javascript objects. It is pure JavaScript Library and works with any web framework. It's not a replacement of JQuery but can work as a supplement providing smart features.


2 Answers

You should use css binding instead of attr for this. Read more about it in the documentation: http://knockoutjs.com/documentation/css-binding.html.

You code will look something like this:

<span class="cls1 cls2" data-bind="text: title, css: myClass" ></span> 

Here is working fiddle: http://jsfiddle.net/vyshniakov/gKaRF/

like image 167
Artem Vyshniakov Avatar answered Sep 29 '22 10:09

Artem Vyshniakov


Using multiple classes:

<span
    class="yourClass"
    data-bind="css: { myClass: (true == true), theirClass: (!true == false), ourClass: true }"
>Thine Classes</span>
like image 30
Cody Avatar answered Sep 29 '22 12:09

Cody