KnockoutJS and CSS transitions

Published July 9, 2012

Something I've noticed with KnockoutJS is that sometimes CSS transitions don't seem to work properly when adding/removing classes from DOM elements with the css binding.

After some investigation, it turns out that Knockout will often re-render the template when such a binding is fired, meaning that you effectively get a new DOM node with the class set (or not set), so the transition doesn't fire. You can use the afterRender callback to find out when the template is re-rendered.

I haven't worked out exactly what circumstances trigger the re-rendering; some situations are fine. I came across it in something I'm writing now and tried to get a simple test case together to submit a bug report, and I just couldn't reproduce it. And of course the situation I had was far too complex to submit. I don't think it's the CSS binding itself that causes it - I wrote a custom dummy binding that didn't do anything (literally just a return statement) and merely having that binding set was enough to cause the problem.

So far I've not found a better workaround than avoiding the the binding and using jQuery (or pure JS) to set the classname, but this is only practical in specific circumstances: it can be hard to associate DOM elements with these workarounds and get them to fire at the right time. Obviously you could also use knockout's events to handle the animation in pure jQuery, but with CSS transitions widely supported now and browsers supporting offloading instructions to the GPU, it seems untidy, no scratch that, _just plain wrong_, to force animation onto the JS interpreter.

Filed under: javascript, programming, knockoutjs

Talk is cheap

Leave a comment:

HTML is not valid. Use:
[url=]Google[/url] [b]bold[/b] [i]italics[/i] [u]underline[/u] [code]code[/code]