packages/lit-dev-content/site/tutorials/content/word-viewer/06.md
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 %}
// word-viewer.ts
@state() private playDirection: -1 | 1 = 1;
// 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 %}
// word-viewer.ts
render() {
...
const idx = ((this.idx % splitWords.length) + splitWords.length) % splitWords.length;
const word = splitWords[idx];
...
}
// 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 %}
// word-viewer.ts
tickToNextWord = () => { this.idx += this.playDirection; };
// word-viewer.js
tickToNextWord = () => { this.idx += this.playDirection; };
{% endswitchable-sample %}
And add a switchPlayDirection method to invert the playDirection.
{% switchable-sample %}
// word-viewer.ts
switchPlayDirection() {
this.playDirection *= -1;
}
// 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 %}
// word-viewer.ts
render() {
...
return html`<pre
@click=${this.switchPlayDirection}
>${word}</pre>`;
}
// 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.