KnockoutJs : Toggling CSS class

A common scenario with Javascript is toggling a set of elements based on the selected element add applying, removing css classes.  You’ll see this on menu items, etc… and in my case where we want to have styled ‘button’s instead of a radio list.

An example of this might be handling the selection of the button and then applying a class and removing any other classes, for example:

$(‘.year_item’).bind(‘click’, function(){
$(“.year_Item”).removeClass(“selected_year”);
$(event.currentTarget).addClass(“selected_year”);
});

In my first attempt at such a toggle with knockoutjs, I followed a similiar route – calling back to my viewmodel :

setYear: function (year, event) {
$(“.year_Item”).removeClass(“selected_year”);
$(event.currentTarget).addClass(“selected_year”);
myViewModel.year(year);
}

The binding in the html looks like this:

<ul data-bind=”foreach: years”>
<li><input data-bind=”text: $data, click: $parent.setYear” type=’button’/></li>
</ul>

This works fine.  However, I can do better – since KnockoutJs supports setting the CSS class on binding.

ie. <div data-bind="css: { profitWarning: currentProfit() < 0 }">

So let’s take this example and show how we can effectively toggle the CSS class based upon the value of the binding – using our example above:

<ul class=”bigButtons” data-bind=”foreach: years”>
<li><input data-bind=”text: $data, click: $parent.year, css:{selected_year: $parent.year() === $data}”  type=’button’/></li>
</ul>

That is it.  No more function required in the viewmodel.  To understand what happens here is to understand the $parent.year click event.  Basically in KnockoutJs 2.0 by default $parent.year takes the $data property as a parameter.  The year binding is set, which in turn triggers the css selection on all the items reevaluating if it should have that CSS appended.

This has proved to be very terse and valuable in our UI.

Edit: I’ve put an example out on jsFiddle: http://jsfiddle.net/sgentile/pRC4c/

Advertisements

4 thoughts on “KnockoutJs : Toggling CSS class

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s