These both act same as CSS hidden and visible. Used to show or hide part of HTML based on values passed to knockout binding.
Bind | Value | Output |
hidden | true | hide |
hidden | false | show |
visible | true | show |
visible | false | hide |
Let’s check code for same.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<div data-bind="visible: showMenu"> <ul> <li>Home</li> <li>Knockout js</li> <li>Magento</li> <li>Shopify</li> <li>Shopware</li> </ul> </div> <script type="text/javascript"> var menuModel = { showMenu: ko.observable(true) // Menu initially visible }; menuModel.showMenu(false); // ... now it's hidden menuModel.showMenu(true); // ... now it's visible again </script> |
In above code, showMenu declared as knockout observable with initial value of true. Later it change value of showMenu to false and true again.
It is visible binding so true value show and if false it hides.
Now let’s look at hidden binding. It works opposite of visible. When showMenu is true it hides and when false then it will show.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<div data-bind="hidden: showMenu"> <ul> <li>Home</li> <li>Knockout js</li> <li>Magento</li> <li>Shopify</li> <li>Shopware</li> </ul> </div> <script type="text/javascript"> var menuModel = { showMenu: ko.observable(false) // Menu initially visible }; menuModel.showMenu(true); // ... now it's hidden menuModel.showMenu(false); // ... now it's visible again </script> |
Using functions and expressions to control element visibility
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<div data-bind="visible: menuArray().length > 0"> <ul> <li>Home</li> <li>Knockout js</li> <li>Magento</li> <li>Shopify</li> <li>Shopware</li> </ul> </div> <script type="text/javascript"> var menuModel = { menuArray: ko.observableArray([]) // Menu initially hidden }; menuModel.menuArray.push("Demo Value"); // Now visible </script> |
Same way you can use for hidden but remember it works opposite.
Additional Information on Parameters:
Value | Conditions | Knockout output |
FALSE | If boolean is false, numeric value is 0, null or undefined | yourElement.style.display to none |
TRUE | If boolean is true, non-null object or array | yourElement.style.display to visible |