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?
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With