I've implemented knockout to display a list of clickable elements functioning as radio buttons. However, when too many elements are added horizontally, it overflows off the page. Currently, I'm breaking them into multiple rows, but this doesn't align with my design vision.
The issue arises because the width of components varies depending on the person's name listed. My goal is to determine how many components can fit within the browser width and hide the excess in another observable array that I can render differently (like using a dropdown). It seems challenging to achieve this using CSS alone since it would require a separate rendering element.
The snippet from my ViewModel resembles this:
self.personList = ko.observableArray(params.personList);
self.visiblePersons = ko.pureComputed(function () {
var viewPortWidth = $("#personListContainer").width();
var personArray = [];
$.each(personList(), function(person) {
var widthOfPersonElement = getRenderedPersonWidth(person); //unsure how to calculate width post-render
viewPortWidth -= widthOfPersonElement;
if (viewPortWidth >= 0) {
personArray.push(person);
}
});
return personArray;
});
self.overflowPersons = ko.pureComputed(function () {
//include all persons not visible in the previous list
//straightforward task
});
Is this realistically achievable? I aim to avoid multiple renders or flickering effects by calculating widths dynamically. For responsive updates upon window resize, I'll need to trigger an event, but tackling the initial step poses a challenge.
UPDATE: After exploring options, resorting to manipulating the DOM seemed necessary. Here's an overview of my approach:
var getRenderedPersonWidth = function(person) {
var displayString = person.FullName + person.ID;
var element = document.createElement('span');
$(element).text(displayString);
$(element).addClass(""); //matching the rendered element's classes
$('#elementtorenderunder').append(element);
var width = $(element).width();
$(element).remove();
return width;
}
Although effective, maintaining class consistency between code and HTML proves cumbersome. It's not elegant, but for now, it serves its purpose.