Back to Lit

06

packages/lit-dev-content/site/tutorials/content/word-viewer/06.md

latest2.7 KB
Original Source

In this section you'll make it so when you click on the word-viewer, the animation plays in reverse.

New internal state is needed to represent the current animation playDirection.

{% switchable-sample %}

ts
// word-viewer.ts

  @state() private playDirection: -1 | 1 = 1;

js
// word-viewer.js

  static properties = {
    playDirection: {state: true},
    ...
  };

  constructor() {
    ...
    this.playDirection = 1;
  }

{% endswitchable-sample %}

Next, update the math that finds the displayed word in the render() method to account for a negative this.idx.

{% switchable-sample %}

ts
// word-viewer.ts

  render() {
    ...
    const idx = ((this.idx % splitWords.length) + splitWords.length) % splitWords.length;
    const word = splitWords[idx];
    ...
  }

js
// word-viewer.js

  render() {
    ...
    const idx = ((this.idx % splitWords.length) + splitWords.length) % splitWords.length;
    const word = splitWords[idx];
    ...
  }

{% endswitchable-sample %}

Change tickToNextWord to choose the next word based on the playDirection.

{% switchable-sample %}

ts
// word-viewer.ts

  tickToNextWord = () => { this.idx += this.playDirection; };

js
// word-viewer.js

  tickToNextWord = () => { this.idx += this.playDirection; };

{% endswitchable-sample %}

And add a switchPlayDirection method to invert the playDirection.

{% switchable-sample %}

ts
// word-viewer.ts

  switchPlayDirection() {
    this.playDirection *= -1;
  }

js
// word-viewer.js

  switchPlayDirection() {
    this.playDirection *= -1;
  }

{% endswitchable-sample %}

Finally, bind this.switchPlayDirection to invoke when the <pre> element is clicked using Lit's declarative event listener syntax.

{% aside "info" "no-header" %}

Event listeners added using the declarative @ syntax in the template are automatically bound to the component, so no arrow function is required. See more in the event docs.

{% endaside %}

{% switchable-sample %}

ts
// word-viewer.ts

  render() {
    ...
    return html`<pre
      @click=${this.switchPlayDirection}
    >${word}</pre>`;
  }

js
// word-viewer.js

  render() {
    ...
    return html`<pre
      @click=${this.switchPlayDirection}
    >${word}</pre>`;
  }

{% endswitchable-sample %}

Click the word-viewer in the preview, the word animation should reverse in direction.

It's difficult to tell what direction the animation is playing in, so in the next section you'll add dynamic styles based on the animation direction.