Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I hide page elements by default but later show them with Knockout?

I'm developing a single-page web app using Knockout and jQuery. The body of the page is divided into different <section>s, each of which corresponds to a certain page; the user will only see one section at once. We're using Knockout's visible binding to hide and show the sections as appropriate, and it works fine.

The problem is that as the page is loading--when the HTML has loaded but Knockout has not yet applied its bindings--all of the sections are visible. This lasts for less than a second, but it is unsightly. I tried to set display: none on the sections so that they would be invisible initially, but there's a quirk with Knockout's visible binding: if the expression evaluates to true, Knockout sets the CSS display property to whatever it would have been without Knockout.

In other words, setting data-bind="visible: true" will not override display: none. This makes sense, since there are often situations when you need to specify the display as either invisible or, say, table-cell, but it's annoying in my case. What's the best way to force Knockout to show my section elements?

like image 402
bdesham Avatar asked Dec 04 '25 23:12

bdesham


1 Answers

It turns out that while Knockout will not override a display: none set in the CSS, e.g.

body > section {
    display: none;
}

it will override the same style directive if it appears in the HTML itself:

<section style="display: none" data-bind="...">

Thus, the solution to my problem was to move the display: none from the CSS file into the style property. Knockout then overrode the property to display my <section> when I wanted it to be displayed.

like image 124
bdesham Avatar answered Dec 06 '25 12:12

bdesham