knockout.js Custom Bindings Custom fade in/fade out visibility binding


This example implements a custom binding that toggles visibility (similar to the existing visible binding), but will utilize jQuery's fading API to animate the transition from visible to invisible.

Custom binding definition:

//Add a custom binding called "fadeVisible" by adding it as a property of ko.bindingHandlers
ko.bindingHandlers.fadeVisible = {
  //On initialization, check to see if bound element should be hidden by default
  'init': function(element, valueAccessor, allBindings, viewModel, bindingContext){
    var show = ko.utils.unwrapObservable(valueAccessor());
    if(!show){ = 'none';
  //On update, see if fade in/fade out should be triggered. Factor in current visibility 
  'update': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
    var show = ko.utils.unwrapObservable(valueAccessor());
    var isVisible = !( == "none");
    if (show && !isVisible){
    }else if(!show && isVisible){

Sample markup with the fadeVisible binding:

<div data-bind="fadeVisible: showHidden()">
  Field 1: <input type="text" name="value1" />
  <br />
  Field 2: <input type="text" name="value2" />
<input data-bind="checked: showHidden" type="checkbox"/> Show hidden

Sample view model:

var ViewModel = function(){
    var self = this;
    self.showHidden = ko.observable(false);

ko.applyBindings(new ViewModel());