Control text color from a collection?

Hi. I’d like to have a text element that displays the contents of a particular field from a specific row in a data collection. This is easy: I just create a dataset that selects that single row, and connect the text element to that dataset picking out the field I’d like to display.

Now the hard part: I want the color of the text element to be specified by a different field in the same row of the collection, so if I change the data in the collection the color of the text changes. I don’t see an easy way of doing this so I hope I’m missing something. I don’t even see how to programmatically change the color of a text element, which would let me do it in front-end code. My only ideas are bad ones, e.g.: Make a text element of each color, then show the appropriate one and hide the others in front-end code based on the content of a different, always-invisible element that’s connected to the appropriate collection field—which assumes that the text content of the element is set before my front-end code runs. Ugh. Any better ideas?

Update: OK, I see how to control color by direct manipulation of an element’s HTML. However, code in the onReady block of the page seems to be executed before the HTML is changed to reflect the dataset connection. How can I get my hands on the page after that connection is made, so that I can see the values from the data collection and modify the color accordingly?

I have a preliminary solution.

The key is that datasets throw an onReady event when they’re loaded. So attach an event handler that gets the color from the data collection’s item and changes the html of the text element accordingly. Moreover, since the dataset retrieves the entire item, it’s simpler NOT to connect the text element to the dataset—just set the text of the element along with the color. Here’s the code, assuming that the dataset always selects a single row from the collection:

$w('#dataset').onReady( () => {
  var item = $w('#dataset').getCurrentItem();
  $w('#text').html = 
     $w('#text').html
                .replace("INITIALTEXT",
                         "<span style=\"color:" 
                           + item.color 
                           + "\">" 
                           + item.text 
                           + "</span>");
});

(INITIALTEXT is the string hardcoded into the text element; it just makes the right place in the html easy to find.) One subtlety: This code needs to be placed within the page’s onReady handler, so that it doesn’t execute until the page is loaded AND the dataset has its data.

Further improvements welcome.