Kapil Garg
Kapil Garg

Reputation: 3210

How to Animate the if body in knockoutjs?

I have one knockoutjs observable variable called "state" and i am using that variable to hide and show content in knockout with if condition like below:

<--if: state()=="login" -->
login content
<--/if-->

<--if: state()=="registration" -->
registration content
<--/if-->

whenever state variable changes it shows or hides the content. So my question is that i want to add animation of toggling behavior when it hides or shows for this. how would i be able to do it?

Upvotes: 0

Views: 649

Answers (4)

stealthwang
stealthwang

Reputation: 954

Top voted answer isn't a solution since it doesn't unrender the elements.

Austins answer doesn't appear to work at all.

See my response in: Animation before 'with' binding update

for a clean workaround I've discovered, replacing 'if' and 'with' with roughly equivalent 'template' bindings.

Upvotes: 0

Rynan
Rynan

Reputation: 481

First, I think you may have some error in your code there(may have just copied it over wrong) but it should be:

<-- ko if: state()=="login" -->
login content
<--/ko-->

<-- ko if: state()=="registration" -->
registration content
<--/ko-->

Second, if you can use jQuery along with binding on elements instead of using virtual elements such as:

<div data-bind="if: state()=="login">

You can utilize Knockout's bindingHandlers. I have created an ifTransition binding which does what you want. Here's a fiddle with the bindingHandler and a sample of it in action:

http://jsfiddle.net/Rynan/vtPT8/

Update

Okay, I updated my fiddle to utilize the virtual elements but you will still have to wrap your login and registration content within a div to get the transition affect you are looking for. Keeping with your comment, that div won't be rendered until the state has changed to whatever it needs to be to display those certain contents so it won't take much memory while it isn't in the correct state.

Upvotes: 0

Austin Fatheree
Austin Fatheree

Reputation: 842

I further updated Anders' fiddle to add the state condition:

http://jsfiddle.net/ujSvb/3/

Upvotes: 0

Anders
Anders

Reputation: 17564

I did a quick fiddle for you.

http://jsfiddle.net/ujSvb/1/

for a more dynamic example

http://jsfiddle.net/ujSvb/2/

Upvotes: 3

Related Questions