Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing css class in knockout.js on mouse click

The knockout.js documentation shows the css binding like this:

<div data-bind="css: { profitWarning: currentProfit() < 0 }">   
    Profit Information
</div>

I need to adapt it to change the css class on mouseclick. How can I do this?

Based on answers below, I am using some code like this:

// CSS class to be applied
<style>
    .bigclass
    {
        width: 200px;
    }

</style>

// Select list inside a jquery .tmpl
<script id='criteriaRowTemplate' type='text/html'>
    <tr>
        <td>
            <select data-bind='click: makeBig, css: {bigclass : SelectHasFocus() > 0}' />
        </td>
    </tr>
</script> 

// Knockout.js Viewmodel
var CriteriaLine = function() {
    this.SearchCriterion = ko.observable();
    this.SelectHasFocus = ko.observable(0);

    // this method is called
    makeBig = function(element) { 
        this.SelectHasFocus(1);            
    };        
};

However, this is not expanding the width of the select list. What am I doing wrong?

like image 816
Yasir Avatar asked Jun 27 '12 21:06

Yasir


People also ask

Can we use CSS class in JavaScript?

The class name can be used by JavaScript to manipulate the specified element while CSS uses that class name to style that element. Hence, in this post, we will go through how to modify CSS classes in JavaScript but first let us set the environment by initializing elements in HTML and then styling that element in CSS.

Is KnockoutJS 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.

What is two way binding in KnockoutJS?

KO is able to create a two-way binding if you use value to link a form element to an Observable property, so that the changes between them are exchanged among them. If you refer a simple property on ViewModel, KO will set the form element's initial state to property value.


1 Answers

Have your click function change an observable variable. For example:

<div data-bind="css: { myclass: newClass() == true }">
   Profit Information
</div>

<button data-bind="click: changeClass">Change Class</button>

<script type="text/javascript">
    var viewModel = {
        newClass: ko.observable(false),
        changeClass: function() {
            viewModel.newClass(true);
        }
    }; 
</script>

Note: You can combine click and css on the same element. For example:

<div databind="click: changeClass, css: { myclass: newClass() == true }"></div>
like image 195
Pakman Avatar answered Oct 01 '22 01:10

Pakman