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


Example

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){
      element.style.display = '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 = !(element.style.display == "none");
    
    if (show && !isVisible){
      $(element).fadeIn(750);
    }else if(!show && isVisible){
      $(element).fadeOut(750);
    }
  }
}

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" />
</div>
<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());