0

I would like to dynamically set the font-size on the root element using a custom Knockout bindinghandler which does a calculation based on the width of the browser window.

When I tried to apply the binding, nothing seemed to happen, so I tried to apply a simple css binding:

<html data-bind="css: { bindinghandlertest: true }">

But the binding handler didn't seem to add the class.

Question: Can KO bindings only be applied to <body> and its children?

Note: I am initializing all bindings on the whole page by simply calling ko.applyBindings(); once on DOM ready, with no parameters at all.

connexo
  • 53,704
  • 14
  • 91
  • 128
  • Out of curiosity, is there some reason you don't want to use CSS media queries to do this? – Kyeotic Sep 02 '16 at 15:22
  • Even if that were possible, this is not what this question is about. It's just what made me stumble across this issue. – connexo Sep 02 '16 at 15:53
  • It is possible. That's one of the primary use cases for media queries: applying different CSS based on the width of the browser. I know you were asking about Knockout, but offering another solution is pretty standard MO here – Kyeotic Sep 02 '16 at 16:32
  • Does this answer your question? [How to get the data-id attribute?](https://stackoverflow.com/questions/5309926/how-to-get-the-data-id-attribute) – Protect children of Donbas2014 Apr 09 '21 at 13:08

1 Answers1

1

You can apply bindings to a specific html element as explained here

Specifically:

Optionally, you can pass a second parameter to define which part of the document you want to search for data-bind attributes. For example, ko.applyBindings(myViewModel, document.getElementById('someElementId'))

In you case, you can them call

ko.applyBindings(myVM, document.documentElement);

by default, the DOM node is the body, as you can see from the source:

rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional

Regis Portalez
  • 4,675
  • 1
  • 29
  • 41