Knockout: How do I toggle visibility of multiple divs on button click?

I want to toggle visibility of multiple divs using knockout. Below is the rough idea of my problem -

<button>Button 1</button>
<button>Button 2</button>
<button>Button 3</button>

<div> Div 1 </div>
<div> Div 2 </div>
<div> Div 3 </div>

By default, 'Div 1' should be visible.

When I click individual buttons it should display only the related divs based on the buttons clicked.

I have gone through the Knockout live examples but not getting how to do this efficiently.

Please help!

Answers:

Answer

The following will do a job for you. It's not ideal, but should give you a platform to work on.

First, everything in Knockout is tied to a view model. You want to be able to control the visibility of 3 divs, so here's a view model which might suit. Like I said, not perfect :)

var buttonVm = new function(){
  var self = this;
  // Flags for visibility
  // Set first to true to cover your "first should be open" req
  self.button1Visible = ko.observable(true);
  self.button2Visible = ko.observable(false);
  self.button3Visible = ko.observable(false);

  self.toggle1 =  function(){
     self.button1Visible(!self.button1Visible());
  }

  self.toggle2 =  function(){
     self.button2Visible(!self.button2Visible());
  }

  self.toggle3 =  function(){
     self.button3Visible(!self.button3Visible());
  }

}

You'll need to change your markup to:-

<!-- events here.  When clicked call the referenced function -->
<button type="button" data-bind="click: toggle1">Button 1</button>
<button type="button" data-bind="click: toggle2">Button 2</button>
<button type="button" data-bind="click: toggle3">Button 3</button>

<!-- Visibility set here -->
<div data-bind="visible: button1Visible"> Div 1 </div>
<div data-bind="visible: button2Visible"> Div 2 </div>
<div data-bind="visible: button3Visible"> Div 3 </div>

Couple of things to note here. First, I've added the type attribute. Without it, the default behaviour of the button will be to try and submit your form.

Tying it all up:-

// Create view model
var vm = new buttonVm();
ko.applyBindings(vm);

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.