Reputation: 1625
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?
Upvotes: 12
Views: 21851
Reputation: 2210
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>
Upvotes: 17
Reputation: 1637
The simplest way is to use a click binding which changes an observable in the callback. You would bind the class appropriately using something like the attr binding
Upvotes: 1
Reputation: 11
I feel the problem is with script tag.
Please find the solution in following link: http://jsfiddle.net/ZmU6g/3/
Upvotes: 1