2

I want to make an HTML element visible based on whether or not another element on the page has a certain class:

function MyViewModel() {
    var self = this;          

    this.showElement = ko.computed(function() {            
        return $('#history').hasClass('active');
    }, this);
}

<li data-bind="visible: showElement">Element Text</li>
<div id="summary" class="tab-pane fade in active"></div>
<div id="history" class="tab-pane fade in"></div>

Any time a tab-pane is clicked, that tab gets the 'active' class. Depending on which tab is active, I'd like to either hide or show the li element. I feel like I'm close, but missing something.

1 Answer 1

3

I wouldn't recommend doing that. The showElement property has no dependencies on any other observables in your view model so it will never get updated.

You should change it so the active class will be applied based on what is selected in your view model. Then you can have your Element Text appear when it should.

Add bindings to your divs to apply the active class based on some conditions and set your element to be visible based on the condition you want:

<div id="summary" class="tab-pane"
     data-bind="click: select, css: { active: summaryActive }">SUMMARY</div>
<div id="history" class="tab-pane"
     data-bind="click: select, css: { active: historyActive }">HISTORY</div>

<li data-bind="visible: historyActive">Element Text</li>

Then set those conditions in your view model:

self.selected = ko.observable(null);
self.summaryActive = ko.computed(function () {
    return self.selected() === 'summary';
});
self.historyActive = ko.computed(function () {
    return self.selected() === 'history';
});

fiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.