Update cell on link click

Greetings - I’m using the HTL template described by @mbostock here and trying to get a cell to update its content when a link within it is clicked.

My minimal example fails because of a ‘circular definition’. Can someone recommend the right way to do this ? The goal is to show some html with a ‘next’ link and when the link is clicked, the html updates to show the next section (with a link, etc).

I’m not sure exactly what you’re trying to do, but below snippet shows “stepping” through some array of html content:

  const options = ['fish', 'cat', 'dog'];
  while (true) {
    for (let animal of options) {
      let go;
      let next = new Promise(resolve => (go = resolve));
      yield html`section for ${animal}: <a href="#" onclick=${go}>click</a> for next`;
      await next;

As you click, this will cycle through the options and reset to the beginning. I think you could probably make that more elegant than above. You could also do it entirely in html, so you render an entire html “app” that sets-up event handler to toggle visibility of the html elements on each click.

1 Like

Thanks @keystroke - this works, though I’m not fully sure why… would you mind adding a few comments ? Also, is it possible to do this with a function call in the onclick handler, rather than a reference to a promise?

Hi @dhowe, if you want a more straightforward implementation using the mutable state, you could do this

display = html`first ${sections[currSection]}: <a href="#" onclick=${() =>
  (mutable currSection = (currSection + 1) % sections.length)}>click</a> for next`
sections = ['One', 'Two', 'Three', 'Four']
mutable currSection = 0

You could also have sections in the same cell as the display

display = {
  const sections = ['One', 'Two', 'Three', 'Four'];
  return html`first ${sections[currSection]}: <a href="#" onclick=${() =>
    (mutable currSection =
      (currSection + 1) % sections.length)}>click</a> for next`;
mutable currSection = 0

Yes, this is much more straightforward, thanks @radames.

But the reason I am asking about a function call is that the sections do not exist in advance, they are generated at click-time. So it seems some code needs to run when the click happens. Any thoughts on how to call a function from the click, which then updates the ‘display’ ?