0

I am using the Knockout js in my project,I need to add multiple css class name to particular tag.below is my code i have three different class how i can add it in knockout css binding kindly suggest.

<img data-bind="attr: { src:ProfileImageSrcName }" class="tabUser profile-Image tabpic" />
3
  • Use the css binding knockoutjs.com/documentation/css-binding.html Commented May 19, 2017 at 13:44
  • have seen it,how i can use multiple class name Commented May 19, 2017 at 13:51
  • Look at my answer below. Commented May 19, 2017 at 14:30

2 Answers 2

3

you can ise css binding like below.

var vm = {
  profileImageSrcName: ko.observable('http://cumbriaskills.wdfiles.com/local--files/files:images/metro_128_chrome.png'),
  isProfilePic: ko.observable(true),
  isTab: ko.observable(true),
  toggleProfile: function() { vm.isProfilePic(!vm.isProfilePic()); },
  toggleTab: function() { vm.isTab(!vm.isTab()); }
};

ko.applyBindings(vm);
.tabUser { width: 100px; height: 100px; object-fit: contain; }
.profile-image { border-radius: 100% } 
.tabPic { box-shadow: 0 2px 6px rgba(0,0,0,0.4) }
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<img data-bind="attr: { src: profileImageSrcName }, 
                css: { 
                  'profile-image': isProfilePic, /* single class */
                  'tabUser tabPic': isTab  /* multiple classes */
                }" />
<br><br>
<button data-bind="click: toggleProfile">Toggle "profile-image" Class</button><br>
<button data-bind="click: toggleTab">Toggle "tabUser" and "tabPic" Classes</button>

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

Comments

1

Use css binding to assign multiple class name.

http://knockoutjs.com/documentation/css-binding.html

var masterVM = (function () {
  var self = this;      
  self.classNames = ko.pureComputed(function(){
    return "className1 className2 className3";
  }, self);
})();

ko.applyBindings(masterVM); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<div class="existingClass" data-bind="css: classNames">
  Inspect this element to see list of the 4 class names.
</div>

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.