0

I want to add a class to an element if the title of the page includes "Home". Currently, I use this:

<li data-bind="css: { 'active': function(){return document.title.indexOf('Home') > -1;}}">

However this does not work, this function does not get executed... How do I make this work?

1 Answer 1

2

Knockout wraps the value in a computed function in a way that resembles this:

Input: "yourClassName": whateverYouPutIn
Output: "yourClassName": ko.computed(function() { return whateverYouPutIn; })

In your case, you put in a function, which will result in a "truethy" value setting the active class. You can fix this by:

Option 1 (quick): Don't wrap it in a function

<li data-bind="css: { 
    'active': document.title.indexOf('Home') > -1
  }"></li>

Option 2 (not recommended): Fix the typo (funciton) and call the function

<li data-bind="css: { 
    'active': (function() {
      return document.title.indexOf('Home') > -1;
     }())
  }"></li>

Option 3: Add these kinds of properties to your viewmodel

var vm = {
  // set when VM is initialized
  isActive: document.title.indexOf("Home"), 
  // if you want to check the title during data-binding
  isActiveDuringBind: function() {
    return document.title.indexOf("Home");
  }
}

With either

<li data-bind="css: {'active': isActive }"></li>

or

<li data-bind="css: {'active': isActiveDuringBind() }"></li>

Note that using the DOM api outside of custom bindings is considered "bad practice"... But in this case I guess you can get away with it...

Note that because there are no observable values being used, your class will not toggle when you change document.title.

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

1 Comment

Thank you for the extended answer, made it work! Sorry for the stupid typo though.

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.