Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockout.js visibility not working when css style is applied

I have an issue where knockout.js 2.0 isn't showing my item when a CSS style is applied to it. It won't update the display with the style applied to it. If it is off it works.

CSS

.success { display:none }

HTML

   <div data-bind="visible: site.signUp.success()" class="success">
     Thanks for signining up.  You will recieve an email from us in the near future.
   </div>

JS

app.viewModel.site.signUp.success(true);
like image 256
Mike Flynn Avatar asked Dec 13 '22 06:12

Mike Flynn


2 Answers

In the period of time before Knockout.js applies bindings, you can prevent the initial rendering/flashing effect by setting the default display style to none.

 <div style="display: none" data-bind="visible: site.signUp.success">
     Thanks for signining up.  You will recieve an email from us in the near future.
 </div>
like image 58
Gregor hall Avatar answered Mar 08 '23 10:03

Gregor hall


I created a fiddle that shows how you can use the css binding in Knockout to do this. http://jsfiddle.net/johnpapa/vwcfT/

Here is the HTML:

Success Flag: <input type="checkbox" data-bind="checked:site.signUp.success"></input>
<div data-bind="visible: site.signUp.success" >
    Thanks for signining up.  You will recieve an email from us in the near future.
</div>

<br/><br/>
<span data-bind="text:site.signUp.success"></span>
<div data-bind="css: { success: site.signUp.success}" >
    Thanks for signining up.  You will recieve an email from us in the near future.
</div>

The first DIV in the example just uses the visible binding, since you dont really need a css class to do this. The second DIV in the example binds to a css class named "success" if the site.signUp.success observable is true. This is more verbose than the first, but could be useful if you needed your css class to do more than just set visibility.

Hope this helps.

Here is the javascript:

var viewModel = {
    site: {
        signUp: {
            success: ko.observable(true)
        }
    }
};

ko.applyBindings(viewModel);
like image 32
John Papa Avatar answered Mar 08 '23 10:03

John Papa