user2274336 user2274336 - 2 months ago 25
CSS Question

How to make Knockout a knockout visible tag use display:none !important

I have a site using both knockout and bootstrap, I need to use the knockout visible data binding to add and remove certain elements based on a given criteria, however , when knockout add's the

style="display:none"
to the
div
it gets overridden by bootstrap as the
hidden-md
and
hidden-lg
use
display:block !important
on smaller screens.

<div class="col-xs-1 hidden-md hidden-lg" data-bind="visible: BooleanValue"></div>


Is there a simple way to make knockout use
style="display:none !important"
so that my values aren't shown?

Cheers.

Answer

You could use the css binding and add a style rule to (the bottom) of your style guide:

ko.applyBindings({booleanValue: ko.observable(true)});
.block {
  display: block !important;
}

.hide-important {
  display: none !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>


<div class="block" data-bind="visible: booleanValue">
  visible binding
</div>

<div class="block" data-bind="css: {'hide-important': !booleanValue()}">
  css binding
</div>

<button data-bind="click: booleanValue.bind(null, !booleanValue())">toggle</button>

Alternatively, you could implement a custom visible binding:

ko.bindingHandlers['importantVisible'] = {
  'update': function(element, valueAccessor) {
    var show = ko.utils.unwrapObservable(valueAccessor());
    if (!show)
      element.style.setProperty("display", "none", "important")
    else
      element.style.display = "";
      
  }
};

ko.applyBindings({ booleanValue: ko.observable(true) });
.block {
  display: block !important;
}

.hide-important {
  display: none !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<div class="block" data-bind="importantVisible: booleanValue">
  importantVisible binding
</div>


<div class="block" data-bind="visible: booleanValue">
  visible binding
</div>

<div class="block" data-bind="css: {'hide-important': !booleanValue()}">
  css binding
</div>

<button data-bind="click: booleanValue.bind(null, !booleanValue())">toggle</button>