Currently, I am encountering an issue with changing the color when a user clicks on a list item using the latest version of knockout js. My goal is to change the color of a list item when it is clicked and maintain that color until another item is clicked, but so far I haven't been successful.
One idea I have is to retrieve the index value of the clicked list item and add a CSS class with inverted colors (color: black, background-color: white).
HTML
<div class="left_pane">
<div class="location_list" data-bind="foreach: locations">
<div data-bind="text: title, click: $parent.is_selected, css: {selected: $parent.current_index == $index }"></div>
</div>
</div>
CSS
.left_pane {
background-color: black;
color: white;
padding-top: 10px;
height: 850px;
}
.location_list {
padding-top: 10px;
padding-bottom: 10px;
cursor: pointer;
cursor: hand;
}
.selected {
background-color: white;
color: black;
}
JavaScript
var locations = [
{'title': 'title01'},
{'title': 'title02'},
{'title': 'title03'},
{'title': 'title04'},
{'title': 'title05'}
];
function InitViewModel() {
// main viewModel
var self = this;
self.current_index = ko.observable('');
console.log(self.current_index());
self.is_selected = function(data, event) {
// save clicked row's index to current_index.
self.current_index($(event.target).index());
console.log(self.current_index());
};
}
ko.applyBindings(new InitViewModel());
Thank you in advance for any support and suggestions provided.